-
Notifications
You must be signed in to change notification settings - Fork 124
/
gorose.go
121 lines (109 loc) · 2.51 KB
/
gorose.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package gorose
import (
"database/sql"
"github.com/gohouse/gorose/v3/builder"
_ "github.com/gohouse/gorose/v3/driver/mysql"
)
type GoRose struct {
Cluster *ConfigCluster
master []*sql.DB
slave []*sql.DB
driver string
prefix string
handlers HandlersChain
}
type HandlerFunc func(*builder.Context)
type HandlersChain []HandlerFunc
//const abortIndex int8 = math.MaxInt8 >> 1
//type handlers struct {
// handlers HandlersChain
// index int8
//}
//
//func (c *handlers) Next() {
// c.index++
// for c.index < int8(len(c.handlers)) {
// c.handlers[c.index](c)
// c.index++
// }
//}
func (g *GoRose) Use(h ...HandlerFunc) *GoRose {
g.handlers = append(g.handlers, h...)
return g
}
//func (dg *GoRose) Use(h ...HandlerFunc) *GoRose {
//}
// Open db
// examples
//
// Open("mysql", "root:root@tcp(localhost:3306)/test?charset=utf8mb4&parseTime=true")
// Open(&Config{...})
// Open(&ConfigCluster{...})
func Open(conf ...any) *GoRose {
var g = GoRose{}
switch len(conf) {
case 1:
if single, ok := conf[0].(*Config); ok {
g.driver = single.Driver
g.prefix = single.Prefix
g.Cluster = &ConfigCluster{WriteConf: []Config{*single}}
if single == nil { // build sql only
//g.ConfigCluster = &ConfigCluster{Prefix: "test_"}
return &g
}
g.master, g.slave = g.Cluster.init()
} else if cluster, ok := conf[0].(*ConfigCluster); ok {
g.driver = cluster.WriteConf[0].Driver
g.prefix = cluster.WriteConf[0].Prefix
g.Cluster = cluster
if cluster == nil { // build sql only
//g.ConfigCluster = &ConfigCluster{Prefix: "test_"}
return &g
}
g.master, g.slave = g.Cluster.init()
} else {
g.driver = "mysql" // for toSql test
}
case 2:
g.driver = conf[0].(string)
db, err := sql.Open(g.driver, conf[1].(string))
if err != nil {
panic(err.Error())
}
g.master = append(g.master, db)
default:
panic("config must be *gorose.ConfigCluster or sql.Open() origin params")
}
return &g
}
func (g *GoRose) Close() (err error) {
if len(g.master) > 0 {
for _, db := range g.master {
err = db.Close()
}
}
if len(g.slave) > 0 {
for _, db := range g.slave {
err = db.Close()
}
}
return
}
func (g *GoRose) MasterDB() *sql.DB {
if len(g.master) == 0 {
return nil
}
return g.master[GetRandomInt(len(g.master))]
}
func (g *GoRose) SlaveDB() *sql.DB {
if len(g.slave) == 0 {
return g.MasterDB()
}
return g.slave[GetRandomInt(len(g.slave))]
}
func (g *GoRose) NewDatabase() *Database {
return NewDatabase(g)
}
func (g *GoRose) NewEngin() *Engin {
return NewEngin(g)
}