@@ -8,6 +8,7 @@ package mysql
88import (
99 gosql "database/sql"
1010 "fmt"
11+ "sync"
1112 "time"
1213
1314 "github.com/github/gh-ost/go/sql"
@@ -33,13 +34,27 @@ func (this *ReplicationLagResult) HasLag() bool {
3334 return this .Lag > 0
3435}
3536
36- func GetDB (mysql_uri string ) (* gosql.DB , error ) {
37- db , err := gosql .Open ("mysql" , mysql_uri )
38- if err == nil {
39- return db , nil
40- } else {
41- return nil , err
37+ // knownDBs is a DB cache by uri
38+ var knownDBs map [string ]* gosql.DB = make (map [string ]* gosql.DB )
39+ var knownDBsMutex = & sync.Mutex {}
40+
41+ func GetDB (migrationUuid string , mysql_uri string ) (* gosql.DB , bool , error ) {
42+ cacheKey := migrationUuid + ":" + mysql_uri
43+
44+ knownDBsMutex .Lock ()
45+ defer func () {
46+ knownDBsMutex .Unlock ()
47+ }()
48+
49+ var exists bool
50+ if _ , exists = knownDBs [cacheKey ]; ! exists {
51+ if db , err := gosql .Open ("mysql" , mysql_uri ); err == nil {
52+ knownDBs [cacheKey ] = db
53+ } else {
54+ return db , exists , err
55+ }
4256 }
57+ return knownDBs [cacheKey ], exists , nil
4358}
4459
4560// GetReplicationLag returns replication lag for a given connection config; either by explicit query
@@ -62,7 +77,10 @@ func GetReplicationLag(informationSchemaDb *gosql.DB, connectionConfig *Connecti
6277func GetMasterKeyFromSlaveStatus (connectionConfig * ConnectionConfig ) (masterKey * InstanceKey , err error ) {
6378 currentUri := connectionConfig .GetDBUri ("information_schema" )
6479 // This function is only called once, okay to not have a cached connection pool
65- db , err := GetDB (currentUri )
80+ db , err := gosql .Open ("mysql" , currentUri )
81+ if err != nil {
82+ return nil , err
83+ }
6684 defer db .Close ()
6785
6886 if err != nil {
0 commit comments