github.com/tuingking/flamingo@v0.0.0-20220403134817-2796ae0e84ca/infra/mysql/mysql.go (about) 1 package mysql 2 3 import ( 4 "context" 5 "database/sql" 6 "fmt" 7 "time" 8 9 _ "github.com/go-sql-driver/mysql" 10 "github.com/pkg/errors" 11 "github.com/sirupsen/logrus" 12 ) 13 14 type MySQL interface { 15 PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) 16 Prepare(query string) (*sql.Stmt, error) 17 ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) 18 Exec(query string, args ...interface{}) (sql.Result, error) 19 QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) 20 Query(query string, args ...interface{}) (*sql.Rows, error) 21 QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row 22 QueryRow(query string, args ...interface{}) *sql.Row 23 BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) 24 Begin() (*sql.Tx, error) 25 Ping() error 26 Close() error 27 SetMaxIdleConns(n int) 28 SetMaxOpenConns(n int) 29 SetConnMaxLifetime(d time.Duration) 30 SetConnMaxIdleTime(d time.Duration) 31 Stats() sql.DBStats 32 } 33 34 type Config struct { 35 Username string 36 Password string 37 HostPort string 38 DBName string 39 40 // Default is unlimited 41 // set to lest than equal to 0 means make it unlimited or default setting, 42 // more open connection means less time taken to perform query 43 MaxOpenConn int 44 45 // MaxIdleConn default is 2 46 // set to lest than equal to 0 means not allow any idle connection, 47 // more idle connection in the pool will improve performance, 48 // since no need to establish connection from scratch) 49 // by set idle connection to 0, a new connection has to be created from scratch for each operation 50 // ! should be <= MaxOpenConn 51 MaxIdleConn int 52 53 // MaxLifetime set max length of time that a connection can be reused for. 54 // Setting to 0 means that there is no maximum lifetime and 55 // the connection is reused forever (which is the default behavior) 56 // the shorter lifetime result in more memory useage 57 // since it will kill the connection and recreate it 58 MaxLifetime time.Duration 59 } 60 61 // New create new MySQL instance 62 func New(cfg Config) MySQL { 63 connectionstr := fmt.Sprintf("%s:%s@tcp(%s)/%s?parseTime=true", cfg.Username, cfg.Password, cfg.HostPort, cfg.DBName) 64 logrus.Infof("connectionstr: %s", connectionstr) 65 66 db, err := sql.Open("mysql", connectionstr) 67 if err != nil { 68 panic(err.Error()) 69 } 70 71 if cfg.MaxOpenConn != 0 { 72 db.SetMaxOpenConns(cfg.MaxOpenConn) 73 } 74 75 if cfg.MaxIdleConn != 0 { 76 db.SetMaxIdleConns(cfg.MaxIdleConn) 77 } 78 79 if err = db.Ping(); err != nil { 80 logrus.Fatal(errors.Wrap(err, "ping mysql")) 81 } 82 83 logrus.Infof("%-7s %s", "MySQL", "✅") 84 85 return db 86 }