/
factory.go
47 lines (40 loc) · 1.27 KB
/
factory.go
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
package mysql
import (
"errors"
log "github.com/sirupsen/logrus"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"github.com/qa-dev/jsonwire-grid/config"
"github.com/qa-dev/jsonwire-grid/pool"
mysqlMigrations "github.com/qa-dev/jsonwire-grid/storage/migrations/mysql"
"github.com/rubenv/sql-migrate"
)
type Factory struct {
}
func (f *Factory) Create(config config.Config) (pool.StorageInterface, error) {
db, err := sqlx.Open("mysql", config.DB.Connection)
if err != nil {
err = errors.New("Database connection error: " + err.Error())
return nil, err
}
err = db.Ping()
if err != nil {
err = errors.New("Database connection not establish: " + err.Error())
return nil, err
}
db.SetMaxIdleConns(0) // this is the root problem! set it to 0 to remove all idle connections
db.SetMaxOpenConns(10) // or whatever is appropriate for your setup.
storage := NewMysqlStorage(db)
migrations := &migrate.AssetMigrationSource{
Asset: mysqlMigrations.Asset,
AssetDir: mysqlMigrations.AssetDir,
Dir: "storage/migrations/mysql",
}
n, err := migrate.Exec(db.DB, "mysql", migrations, migrate.Up)
if err != nil {
err = errors.New("Migrations failed, " + err.Error())
return nil, err
}
log.Infof("Applied %d migrations!\n", n)
return storage, nil
}