forked from go-gorm/sharding
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn_pool.go
108 lines (84 loc) · 2.52 KB
/
conn_pool.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
package sharding
import (
"context"
"database/sql"
"gorm.io/gorm"
)
// ConnPool Implement a ConnPool for replace db.Statement.ConnPool in Gorm
type ConnPool struct {
// db, This is global db instance
sharding *Sharding
gorm.ConnPool
}
func (pool *ConnPool) String() string {
return "gorm:sharding:conn_pool"
}
func (pool ConnPool) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) {
return pool.ConnPool.PrepareContext(ctx, query)
}
func (pool ConnPool) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
ftQuery, stQuery, table, err := pool.sharding.resolve(query, args...)
if err != nil {
return nil, err
}
pool.sharding.querys.Store("last_query", stQuery)
if table != "" {
if r, ok := pool.sharding.configs[table]; ok {
if r.DoubleWrite {
pool.ConnPool.ExecContext(ctx, ftQuery, args...)
}
}
}
return pool.ConnPool.ExecContext(ctx, stQuery, args...)
}
// https://github.com/go-gorm/gorm/blob/v1.21.11/callbacks/query.go#L18
func (pool ConnPool) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) {
ftQuery, stQuery, table, err := pool.sharding.resolve(query, args...)
if err != nil {
return nil, err
}
pool.sharding.querys.Store("last_query", stQuery)
if table != "" {
if r, ok := pool.sharding.configs[table]; ok {
if r.DoubleWrite {
pool.ConnPool.ExecContext(ctx, ftQuery, args...)
}
}
}
return pool.ConnPool.QueryContext(ctx, stQuery, args...)
}
func (pool ConnPool) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row {
_, query, _, _ = pool.sharding.resolve(query, args...)
pool.sharding.querys.Store("last_query", query)
return pool.ConnPool.QueryRowContext(ctx, query, args...)
}
// BeginTx Implement ConnPoolBeginner.BeginTx
func (pool *ConnPool) BeginTx(ctx context.Context, opt *sql.TxOptions) (gorm.ConnPool, error) {
if basePool, ok := pool.ConnPool.(gorm.ConnPoolBeginner); ok {
return basePool.BeginTx(ctx, opt)
}
return pool, nil
}
// Implement TxCommitter.Commit
func (pool *ConnPool) Commit() error {
if _, ok := pool.ConnPool.(*sql.Tx); ok {
return nil
}
if basePool, ok := pool.ConnPool.(gorm.TxCommitter); ok {
return basePool.Commit()
}
return nil
}
// Implement TxCommitter.Rollback
func (pool *ConnPool) Rollback() error {
if _, ok := pool.ConnPool.(*sql.Tx); ok {
return nil
}
if basePool, ok := pool.ConnPool.(gorm.TxCommitter); ok {
return basePool.Rollback()
}
return nil
}
func (pool *ConnPool) Ping() error {
return nil
}