-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyrose.go
119 lines (100 loc) · 2.26 KB
/
myrose.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
package myrose
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
//"fmt"
"regexp"
)
type Connection struct {
DB *sql.DB
Tx *sql.Tx
Transaction bool
GlobalId int64
Fields map[string][]string
FunctionRegxp *regexp.Regexp
AllowNative bool
}
type Updata struct {
field string
operation string
value interface{}
}
var dbConnection *Connection
func newConnection(dsn string) (*Connection, error) {
db, err := sql.Open("mysql", dsn)
if err != nil {
return nil, err
}
if dbConnection == nil {
dbConnection = new(Connection)
}
dbConnection.DB = db
dbConnection.Fields = make(map[string][]string)
dbConnection.FunctionRegxp = regexp.MustCompile(`([A-Za-z0-9_]+?)\((.*)\)`)
return dbConnection, nil
}
//dsn format: root:@tcp(localhost:3306)/test?charset=utf8
func New(dsn string) (*Connection, error) {
if dbConnection != nil {
err := dbConnection.DB.Ping()
if err == nil {
return dbConnection, nil
} else {
return newConnection(dsn)
}
} else {
return newConnection(dsn)
}
}
func NewData() map[string]interface{} {
return make(map[string]interface{})
}
func UpdateData(field string, operation string, value interface{}) Updata {
return Updata{field:field, operation:operation, value:value}
}
func (this *Connection) SetMaxIdleConns(n int) {
this.DB.SetMaxIdleConns(10)
}
func (this *Connection) SetMaxOpenConns(n int) {
this.DB.SetMaxOpenConns(50)
}
func (this *Connection) FlushTableCache() {
this.Fields = make(map[string][]string)
}
func (this *Connection) EnableNativeQuery() {
this.AllowNative = true
}
func (this *Connection) DisableNativeQuery() {
this.AllowNative = false
}
func (this *Connection) Close() error {
return this.DB.Close()
}
func (this *Connection) Ping() error {
return this.DB.Ping()
}
func (this *Connection) Begin() error {
tx, err := this.DB.Begin()
if err == nil {
this.Tx = tx
this.Transaction = true
}
return err
}
func (this *Connection) Commit() error {
err := this.Tx.Commit()
if err == nil {
this.Transaction = false
}
return err
}
func (this *Connection) Rollback() error {
err := this.Tx.Rollback()
if err == nil {
this.Transaction = false
}
return err
}
func (this *Connection) Table(name string) *Table {
return new(Table).Init(name, this)
}