-
Notifications
You must be signed in to change notification settings - Fork 1
/
node.go
364 lines (301 loc) · 11.1 KB
/
node.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package makroud
import (
"context"
"database/sql"
"strings"
"time"
"github.com/gofrs/uuid"
)
// Forked from github.com/heetch/sqalx
// Node is a components that allows to seamlessly create nested transactions and to avoid thinking about whether
// or not a function is called within a transaction.
// With this, you can easily create reusable and composable functions that can be called within or out of
// transactions and that can create transactions themselves.
type Node interface {
// ----------------------------------------------------------------------------
// Query
// ----------------------------------------------------------------------------
// Exec executes a statement using given arguments. The query shouldn't return rows.
Exec(query string, args ...interface{}) (sql.Result, error)
// ExecContext executes a statement using given arguments. The query shouldn't return rows.
ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
// Query executes a statement that returns rows using given arguments.
Query(query string, args ...interface{}) (*sql.Rows, error)
// QueryContext executes a statement that returns rows using given arguments.
QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
// QueryRow executes a statement that returns at most one row using given arguments.
QueryRow(query string, args ...interface{}) *sql.Row
// QueryRowContext executes a statement that returns at most one row using given arguments.
QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
// Prepare creates a prepared statement for later queries or executions.
// Multiple queries or executions may be run concurrently from the returned statement.
Prepare(query string) (*sql.Stmt, error)
// PrepareContext creates a prepared statement for later queries or executions.
// Multiple queries or executions may be run concurrently from the returned statement.
PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
// ----------------------------------------------------------------------------
// Connection
// ----------------------------------------------------------------------------
// DriverName returns the driver name used by this connector.
DriverName() string
// Ping verifies that the underlying connection is healthy.
Ping() error
// PingContext verifies that the underlying connection is healthy.
PingContext(ctx context.Context) error
// Close closes the underlying connection.
Close() error
// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
// Expired connections may be closed lazily before reuse.
SetConnMaxLifetime(duration time.Duration)
// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
SetMaxIdleConns(number int)
// SetMaxOpenConns sets the maximum number of open connections to the database.
SetMaxOpenConns(number int)
// EnableSavepoint activate PostgreSQL savepoints for nested transactions.
EnableSavepoint(enabled bool)
// Stats returns database statistics.
Stats() sql.DBStats
// ----------------------------------------------------------------------------
// Transaction
// ----------------------------------------------------------------------------
// Begin starts a new transaction.
//
// The default isolation level is dependent on the driver.
Begin() (Node, error)
// BeginTx begins a new transaction.
//
// The provided context is used until the transaction is committed or rolled back.
// If the context is canceled, the sql package will roll back the transaction.
// Commit will return an error if the context provided to BeginTx is canceled.
//
// The provided TxOptions is optional and may be nil if defaults should be used.
// If a non-default isolation level is used that the driver doesn't support, an error will be returned.
BeginTx(ctx context.Context, opts *sql.TxOptions) (Node, error)
// Rollback rollbacks the associated transaction.
Rollback() error
// Commit commits the associated transaction.
Commit() error
// ----------------------------------------------------------------------------
// System
// ----------------------------------------------------------------------------
// Tx returns the underlying transaction.
Tx() *sql.Tx
// DB returns the underlying connection.
DB() *sql.DB
}
type node struct {
driver string
db *sql.DB
tx *sql.Tx
savePointID string
savePointEnabled bool
nested bool
}
// Connect connects to a database and verifies connection with a ping.
func Connect(driver string, dsn string) (Node, error) {
db, err := sql.Open(driver, dsn)
if err != nil {
return nil, err
}
err = db.Ping()
if err != nil {
// the connection has been opened within this function, we must close it
// on error.
_ = db.Close()
return nil, err
}
node := &node{
driver: driver,
db: db,
}
return node, nil
}
// NewNode returns a new Node.
func NewNode(db *sql.DB) Node {
return &node{db: db}
}
// DriverName returns the driver name used by this connector.
func (node *node) DriverName() string {
return node.driver
}
// Ping verifies that the underlying connection is healthy.
func (node *node) Ping() error {
return node.db.Ping()
}
// PingContext verifies that the underlying connection is healthy.
func (node *node) PingContext(ctx context.Context) error {
return node.db.PingContext(ctx)
}
// Close closes the underlying connection.
func (node *node) Close() error {
return node.db.Close()
}
// Begin starts a new transaction.
//
// The default isolation level is dependent on the driver.
func (node *node) Begin() (Node, error) {
return node.BeginTx(context.Background(), nil)
}
// BeginTx begins a new transaction.
//
// The provided context is used until the transaction is committed or rolled back.
// If the context is canceled, the sql package will roll back the transaction.
// Commit will return an error if the context provided to BeginTx is canceled.
//
// The provided TxOptions is optional and may be nil if defaults should be used.
// If a non-default isolation level is used that the driver doesn't support, an error will be returned.
func (node *node) BeginTx(ctx context.Context, opts *sql.TxOptions) (Node, error) {
clone := node.clone()
switch {
case clone.tx == nil:
// Create new transaction.
tx, err := clone.db.BeginTx(ctx, opts)
if err != nil {
return nil, err
}
clone.tx = tx
case clone.savePointEnabled:
// Already in a transaction: using savepoints
clone.nested = true
// Savepoints name must start with a char and cannot contain dashes (-)
clone.savePointID = "sp_" + strings.Replace(uuid.Must(uuid.NewV1()).String(), "-", "_", -1)
_, err := node.tx.Exec("SAVEPOINT " + clone.savePointID)
if err != nil {
return nil, err
}
default:
// Already in a transaction: reusing current one.
clone.nested = true
}
return clone, nil
}
// Commit commits the associated transaction.
func (node *node) Commit() (err error) {
if node.tx == nil {
return ErrCommitNotInTransaction
}
if node.savePointID != "" {
_, err = node.tx.Exec("RELEASE SAVEPOINT " + node.savePointID)
if err != nil {
return err
}
} else if !node.nested {
err = node.tx.Commit()
if err != nil {
return err
}
}
node.tx = nil
return nil
}
// Rollback rollbacks the associated transaction.
func (node *node) Rollback() (err error) {
if node.tx == nil {
return nil
}
if node.savePointEnabled && node.savePointID != "" {
_, err = node.tx.Exec("ROLLBACK TO SAVEPOINT " + node.savePointID)
if err != nil {
return err
}
} else if !node.nested {
err = node.tx.Rollback()
if err != nil {
return err
}
}
node.tx = nil
return nil
}
// Tx returns the underlying transaction.
func (node *node) Tx() *sql.Tx {
return node.tx
}
// DB returns the underlying transaction.
func (node *node) DB() *sql.DB {
return node.db
}
// Exec executes a statement using given arguments. The query shouldn't return rows.
func (node *node) Exec(query string, args ...interface{}) (sql.Result, error) {
if node.tx == nil {
return node.db.Exec(query, args...)
}
return node.tx.Exec(query, args...)
}
// ExecContext executes a statement using given arguments. The query shouldn't return rows.
func (node *node) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
if node.tx == nil {
return node.db.ExecContext(ctx, query, args...)
}
return node.tx.ExecContext(ctx, query, args...)
}
// Query executes a statement that returns rows using given arguments.
func (node *node) Query(query string, args ...interface{}) (*sql.Rows, error) {
if node.tx == nil {
return node.db.Query(query, args...)
}
return node.tx.Query(query, args...)
}
// QueryContext executes a statement that returns rows using given arguments.
func (node *node) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) {
if node.tx == nil {
return node.db.QueryContext(ctx, query, args...)
}
return node.tx.QueryContext(ctx, query, args...)
}
// QueryRow executes a statement that returns at most one row using given arguments.
func (node *node) QueryRow(query string, args ...interface{}) *sql.Row {
if node.tx == nil {
return node.db.QueryRow(query, args...)
}
return node.tx.QueryRow(query, args...)
}
// QueryRowContext executes a statement that returns at most one row using given arguments.
func (node *node) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row {
if node.tx == nil {
return node.db.QueryRowContext(ctx, query, args...)
}
return node.tx.QueryRowContext(ctx, query, args...)
}
// Prepare creates a prepared statement for later queries or executions.
// Multiple queries or executions may be run concurrently from the returned statement.
func (node *node) Prepare(query string) (*sql.Stmt, error) {
if node.tx == nil {
return node.db.Prepare(query)
}
return node.tx.Prepare(query)
}
// PrepareContext creates a prepared statement for later queries or executions.
// Multiple queries or executions may be run concurrently from the returned statement.
func (node *node) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) {
if node.tx == nil {
return node.db.PrepareContext(ctx, query)
}
return node.tx.PrepareContext(ctx, query)
}
// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
// Expired connections may be closed lazily before reuse.
func (node *node) SetConnMaxLifetime(duration time.Duration) {
node.db.SetConnMaxLifetime(duration)
}
// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
func (node *node) SetMaxIdleConns(number int) {
node.db.SetMaxIdleConns(number)
}
// SetMaxOpenConns sets the maximum number of open connections to the database.
func (node *node) SetMaxOpenConns(number int) {
node.db.SetMaxOpenConns(number)
}
// EnableSavepoint activates PostgreSQL savepoints for nested transactions.
func (node *node) EnableSavepoint(enabled bool) {
node.savePointEnabled = enabled
}
// Stats returns database statistics.
func (node *node) Stats() sql.DBStats {
return node.db.Stats()
}
// clone clones current node.
func (node *node) clone() *node {
clone := *node
return &clone
}