-
Notifications
You must be signed in to change notification settings - Fork 0
/
SQL_PostgreSQL.go
269 lines (224 loc) · 6.88 KB
/
SQL_PostgreSQL.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package sdk
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"strings"
"sync"
"github.com/lib/pq"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/driver/pgdriver"
)
// nolint: gochecknoglobals
var (
ErrMultipleCommands = errors.New("Multiple commands")
ErrInvalidCommand = errors.New("Invalid command")
)
func PostgreSQLArray(array interface{}) interface {
driver.Valuer
sql.Scanner
} {
return struct {
driver.Valuer
sql.Scanner
}{
v{pq.Array(array)},
s{pgdialect.Array(array)},
}
}
type v struct{ driver.Valuer }
func (v v) Value() (driver.Value, error) { return v.Valuer.Value() }
type s struct{ sql.Scanner }
func (s s) Scan(src interface{}) error { return s.Scanner.Scan(src) }
// -----------------------------------------------------------------------------
// RoundRobin
// -----------------------------------------------------------------------------
// sqlRoundRobin consists of multiple *sql.DB connection, assuming the first element
// of sources is a READ/WRITE access and the rest is READ-ONLY access.
type sqlRoundRobin struct {
SQL
conns []SQLConn
index sqlRoundRobinIndex
}
type sqlRoundRobinIndex struct {
int
*sync.Mutex
}
// OpenWithDSN will open connection from the given dsn string with URL format, note
// that any error when opening the database should result in a panic.
func (SQL) OpenWithDSN(ctx context.Context, dsn string) (conn *sql.DB, err error) {
driverName := strings.Split(dsn+"://", "://")[0]
switch driverName {
case "postgres", "postgresql":
conn = sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn)))
if conn == nil {
return nil, ErrInvalidDatabase
}
default:
conn, err = sql.Open(driverName, dsn)
if err != nil {
return nil, err
} else if conn == nil {
return nil, ErrInvalidDatabase
}
}
return conn, nil
}
// NewRoundRobin will reduce multiple connections into one with RoundRobin style.
func (SQL) NewRoundRobin(ctx context.Context, conns ...SQLConn) SQLConn {
if l := len(conns); l < 1 {
// this is because we expect that `Add` should connect to at least one
// database connection to act as primary conn
panic("empty database")
}
return &sqlRoundRobin{SQL{}, conns, sqlRoundRobinIndex{0, new(sync.Mutex)}}
}
// BeginTx READ+WRITE database.
func (rr *sqlRoundRobin) BeginTx(ctx context.Context, opts *sql.TxOptions) (tx *sql.Tx, err error) {
conn, err := rr.get(0)
if err != nil {
return nil, err
}
return conn.BeginTx(ctx, opts)
}
// Close all databases.
func (rr *sqlRoundRobin) Close() (err error) {
errs := new(ListError)
for i := range rr.conns {
errs = errs.Add(rr.conns[i].Close())
}
return errs.Err()
}
// PingContext all databases.
func (rr *sqlRoundRobin) PingContext(ctx context.Context) (err error) {
errs := new(ListError)
for i := range rr.conns {
errs = errs.Add(rr.conns[i].PingContext(ctx))
}
return errs.Err()
}
// PrepareContext valid queries are DDL, DML & SELECT.
func (rr *sqlRoundRobin) PrepareContext(ctx context.Context, query string) (stmt *sql.Stmt, err error) {
query = rr.RemoveComment(query)
conn := SQLConn(nil)
if rr.IsMultipleCommand(query) {
return nil, fmt.Errorf("database: %w", ErrMultipleCommands)
} else if !rr.IsValidCommand(query) {
return nil, fmt.Errorf("database: %w: %q", ErrInvalidCommand, query)
}
if rr.IsDDLCommand(query) {
conn, err = rr.get(0)
} else if rr.IsDMLCommand(query) {
conn, err = rr.get(0)
} else if rr.IsSELECTCommand(query) {
conn, err = rr.get(-2)
} else {
return nil, fmt.Errorf("database: %w: %q", ErrInvalidCommand, query)
}
if err != nil {
return nil, err
}
return conn.PrepareContext(ctx, query)
}
// ExecContext valid queries are DDL & DML.
func (rr *sqlRoundRobin) ExecContext(ctx context.Context, query string, args ...interface{}) (res sql.Result, err error) {
query = rr.RemoveComment(query)
conn := SQLConn(nil)
if rr.IsMultipleCommand(query) {
return nil, fmt.Errorf("database: %w", ErrMultipleCommands)
} else if !rr.IsValidCommand(query) {
return nil, fmt.Errorf("database: %w: %q", ErrInvalidCommand, query)
}
if rr.IsDDLCommand(query) {
conn, err = rr.get(0)
} else if rr.IsDMLCommand(query) {
conn, err = rr.get(0)
} else if rr.IsSELECTCommand(query) {
return nil, fmt.Errorf("database: %w: %q", ErrInvalidCommand, query)
} else {
return nil, fmt.Errorf("database: %w: %q", ErrInvalidCommand, query)
}
if err != nil {
return nil, err
}
return conn.ExecContext(ctx, query, args...)
}
// QueryContext valid queries are SELECT.
func (rr *sqlRoundRobin) QueryContext(ctx context.Context, query string, args ...interface{}) (rows *sql.Rows, err error) {
query = rr.RemoveComment(query)
conn := SQLConn(nil)
if rr.IsMultipleCommand(query) {
return nil, fmt.Errorf("database: %w", ErrMultipleCommands)
} else if !rr.IsValidCommand(query) {
return nil, fmt.Errorf("database: %w: %q", ErrInvalidCommand, query)
}
if rr.IsSELECTCommand(query) {
conn, err = rr.get(-2)
} else if rr.IsDDLCommand(query) {
return nil, fmt.Errorf("database: %w: %q", ErrInvalidCommand, query)
} else if rr.IsDMLCommand(query) {
return nil, fmt.Errorf("database: %w: %q", ErrInvalidCommand, query)
} else {
return nil, fmt.Errorf("database: %w: %q", ErrInvalidCommand, query)
}
if err != nil {
return nil, err
}
return conn.QueryContext(ctx, query, args...)
}
// QueryRowContext valid queries are SELECT.
func (rr *sqlRoundRobin) QueryRowContext(ctx context.Context, query string, args ...interface{}) (row *sql.Row) {
query = rr.RemoveComment(query)
conn := SQLConn(nil)
if rr.IsMultipleCommand(query) {
return nil
} else if !rr.IsValidCommand(query) {
return nil
}
if rr.IsSELECTCommand(query) {
conn, _ = rr.get(-2)
} else if rr.IsDDLCommand(query) {
return nil
} else if rr.IsDMLCommand(query) {
return nil
} else {
return nil
}
return conn.QueryRowContext(ctx, query, args...)
}
// get will return a new Conn that balanced using roundRobin
//
// rr.get(0) -> direct READ+WRITE
// rr.get(1..n) -> direct READ-ONLY
// rr.get(-1) -> roundRobin READ+WRITE and READ-ONLY
// rr.get(-2) -> roundRobin READ-ONLY
func (rr *sqlRoundRobin) get(i int) (SQLConn, error) {
l := len(rr.conns)
switch {
case l == 1: // only one
rr.index.int = 0
case i >= 0 && l > i: // direct
rr.index.int = i
case (i == -1 || i == -2) && l > 1: // roundRobin
rr.index.Lock()
if rr.index.int++; rr.index.int >= l {
switch i {
case -1: // roundRobin READ/WRITE and READ-ONLY
rr.index.int = 0
case -2: // roundRobin READ-ONLY
rr.index.int = 1
}
}
rr.index.Unlock()
default:
return nil, &SQLRoundRobinError{l, i}
}
return rr.conns[rr.index.int], nil
}
// SQLRoundRobinError reporting issue when getting from set of Conn from SQLRoundRobin.
type SQLRoundRobinError struct{ Total, Index int }
func (e *SQLRoundRobinError) Error() string {
return fmt.Sprintf("database: Unable to connect to database on index %d with total %d element(s).", e.Index, e.Total)
}