-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathapi_mysql.go
76 lines (62 loc) · 1.31 KB
/
api_mysql.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package db
import (
"database/sql"
"sync"
_ "github.com/go-sql-driver/mysql"
)
type luaMySQL struct {
config *dbConfig
sync.Mutex
db *sql.DB
}
var (
sharedMySQL = make(map[string]*luaMySQL, 0)
sharedMySQLLock = &sync.Mutex{}
)
func init() {
RegisterDriver(`mysql`, &luaMySQL{})
}
func (mysql *luaMySQL) constructor(config *dbConfig) (luaDB, error) {
sharedMySQLLock.Lock()
defer sharedMySQLLock.Unlock()
if config.sharedMode {
result, ok := sharedMySQL[config.connString]
if ok {
return result, nil
}
}
db, err := sql.Open(`mysql`, config.connString)
if err != nil {
return nil, err
}
result := &luaMySQL{config: config}
db.SetMaxIdleConns(config.maxOpenConns)
db.SetMaxOpenConns(config.maxOpenConns)
result.db = db
if config.sharedMode {
sharedMySQL[config.connString] = result
}
return result, nil
}
func (mysql *luaMySQL) getDB() *sql.DB {
mysql.Lock()
defer mysql.Unlock()
return mysql.db
}
func (mysql *luaMySQL) getTXOptions() *sql.TxOptions {
return &sql.TxOptions{ReadOnly: mysql.config.readOnly}
}
func (mysql *luaMySQL) closeDB() error {
mysql.Lock()
defer mysql.Unlock()
err := mysql.db.Close()
if err != nil {
return err
}
if mysql.config.sharedMode {
sharedMySQLLock.Lock()
delete(sharedMySQL, mysql.config.connString)
sharedMySQLLock.Unlock()
}
return nil
}