github.com/profzone/eden-framework@v1.0.10/pkg/client/mysql/mysql.go (about)

     1  package mysql
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/profzone/eden-framework/pkg/sqlx"
     6  	"github.com/profzone/eden-framework/pkg/sqlx/mysqlconnector"
     7  	"github.com/profzone/envconfig"
     8  	"io"
     9  	"net/url"
    10  	"time"
    11  )
    12  
    13  type MySQL struct {
    14  	Name            string
    15  	Host            string
    16  	Port            int
    17  	User            string
    18  	Password        envconfig.Password
    19  	Extra           string
    20  	PoolSize        int
    21  	ConnMaxLifetime envconfig.Duration
    22  	Retry
    23  	Database *sqlx.Database `json:"-" ignored:"true"`
    24  
    25  	*sqlx.DB `json:"-" ignored:"true"`
    26  }
    27  
    28  func (m *MySQL) SetDefaults() {
    29  	if m.Port == 0 {
    30  		m.Port = 3306
    31  	}
    32  
    33  	if m.PoolSize == 0 {
    34  		m.PoolSize = 10
    35  	}
    36  
    37  	if m.ConnMaxLifetime == 0 {
    38  		m.ConnMaxLifetime = envconfig.Duration(1 * time.Hour)
    39  	}
    40  
    41  	if m.Extra == "" {
    42  		values := url.Values{}
    43  		values.Set("charset", "utf8")
    44  		values.Set("parseTime", "true")
    45  		values.Set("interpolateParams", "true")
    46  		values.Set("autocommit", "true")
    47  		values.Set("loc", "Local")
    48  		m.Extra = values.Encode()
    49  	}
    50  }
    51  
    52  func (m *MySQL) URL() string {
    53  	password := m.Password
    54  	if password != "" {
    55  		password = ":" + password
    56  	}
    57  	return fmt.Sprintf("%s%s@tcp(%s:%d)", m.User, password, m.Host, m.Port)
    58  }
    59  
    60  func (m *MySQL) Connect() error {
    61  	m.SetDefaults()
    62  	db := m.Database.OpenDB(&mysqlconnector.MysqlConnector{
    63  		Host:  m.URL(),
    64  		Extra: m.Extra,
    65  	})
    66  	db.SetMaxOpenConns(m.PoolSize)
    67  	db.SetMaxIdleConns(m.PoolSize / 2)
    68  	db.SetConnMaxLifetime(time.Duration(m.ConnMaxLifetime))
    69  	m.DB = db
    70  
    71  	return nil
    72  }
    73  
    74  func (m *MySQL) Init() {
    75  	if m.DB == nil {
    76  		m.Do(m.Connect)
    77  	}
    78  }
    79  
    80  func (m *MySQL) Refresh() {
    81  	// TODO use pool to prevent close the connection immediately
    82  	if m.DB != nil {
    83  		if closer, ok := m.DB.SqlExecutor.(io.Closer); ok {
    84  			closer.Close()
    85  		}
    86  	}
    87  	m.Do(m.Connect)
    88  }
    89  
    90  func (m *MySQL) Get() *sqlx.DB {
    91  	if m.DB == nil {
    92  		panic(fmt.Errorf("get db before init"))
    93  	}
    94  	return m.DB
    95  }