-
Notifications
You must be signed in to change notification settings - Fork 0
/
msqlconn_service.go
89 lines (81 loc) · 1.82 KB
/
msqlconn_service.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
package msqlconn
import (
"context"
"fmt"
)
type MysqlService interface {
CreateDatabase(ctx context.Context) (int64, error)
CreateDatabaseWith(ctx context.Context, db string) (int64, error)
ExecuteBatch(statements []string) error
ExecuteBatchWithTransaction(statements []string) error
}
type msqlServiceImpl struct {
mysqlConn *MySql
}
func NewMysqlService(mysqlConn *MySql) MysqlService {
s := &msqlServiceImpl{
mysqlConn: mysqlConn,
}
return s
}
func (m *msqlServiceImpl) CreateDatabase(ctx context.Context) (int64, error) {
return m.CreateDatabaseWith(ctx, m.mysqlConn.Config.Database)
}
func (m *msqlServiceImpl) CreateDatabaseWith(ctx context.Context, db string) (int64, error) {
if !m.mysqlConn.State.IsConnected {
return -1, m.mysqlConn.State.Error
}
response, err := m.mysqlConn.conn.ExecContext(ctx, fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", db))
if err != nil {
return -1, err
}
no, err := response.RowsAffected()
return no, err
}
func (p *msqlServiceImpl) ExecuteBatch(statements []string) error {
if len(statements) == 0 {
return fmt.Errorf("missing statements")
}
tx, err := p.mysqlConn.conn.Begin()
if err != nil {
return err
}
defer func() {
if p := recover(); p != nil {
tx.Rollback()
panic(p)
} else if err != nil {
tx.Rollback()
} else {
err = tx.Commit()
}
}()
for _, statement := range statements {
_, err := tx.Exec(statement)
if err != nil {
return err
}
}
return nil
}
func (p *msqlServiceImpl) ExecuteBatchWithTransaction(statements []string) error {
tx, err := p.mysqlConn.conn.Begin()
if err != nil {
return err
}
defer func() {
if p := recover(); p != nil {
tx.Rollback()
panic(p)
} else if err != nil {
tx.Rollback()
} else {
err = tx.Commit()
}
}()
err = p.ExecuteBatch(statements)
if err != nil {
return err
}
return nil
}