1 // Use Connector to specify how to connect to MySQL.
2 // Then get a sql.*DB from it which is returned to the app..
9 _ "github.com/go-sql-driver/mysql"
11 "github.com/sjmudd/mysql_defaults_file"
12 "github.com/sjmudd/pstop/lib"
17 db = "performance_schema"
24 type Connector struct {
26 components map[string] string
31 // return the database handle
32 func (c Connector) Handle() *sql.DB {
36 // return the defaults file
37 func (c Connector) DefaultsFile() string {
38 return c.defaults_file
41 // set the defaults file
42 func (c *Connector) SetDefaultsFile( defaults_file string ) {
43 c.defaults_file = defaults_file
47 func (c *Connector) SetComponents(components map[string]string) {
48 c.components = components
51 // things to do after connecting
52 func (c *Connector) postConnectStuff() {
53 if err := c.dbh.Ping(); err != nil {
57 // deliberately limit the pool size to 5 to avoid "problems" if any queries hang.
58 c.dbh.SetMaxOpenConns(5) // hard-coded value!
61 // determine how we want to connect
62 func (c *Connector) SetConnectBy( connectHow int ) {
63 c.connectBy = connectHow
66 // make the database connection
67 func (c *Connector) Connect() {
71 case c.connectBy == DEFAULTS_FILE:
72 lib.Logger.Println("connect_by_defaults_file() connecting to database")
74 c.dbh, err = mysql_defaults_file.OpenUsingDefaultsFile(sql_driver, c.defaults_file, db)
78 case c.connectBy == COMPONENTS:
79 lib.Logger.Println("connect_by_components() connecting to database")
81 new_dsn := mysql_defaults_file.BuildDSN(c.components, db)
82 c.dbh, err = sql.Open(sql_driver, new_dsn)
87 log.Fatal("Connector.Connect() c.connectBy not DEFAULTS_FILE/COMPONENTS")
92 // Connect to MySQL using various component parts needed to make the dsn.
93 func (c *Connector) ConnectByComponents(components map[string]string) {
94 c.SetComponents(components)
95 c.SetConnectBy(COMPONENTS)
99 // Connect to the database with the given defaults-file, or ~/.my.cnf if not provided.
100 func (c *Connector) ConnectByDefaultsFile(defaults_file string) {
101 c.SetDefaultsFile(defaults_file)
102 c.SetConnectBy(DEFAULTS_FILE)