/
database.go
734 lines (597 loc) · 17.2 KB
/
database.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
package sqladapter
import (
"context"
"database/sql"
"math"
"strconv"
"sync"
"sync/atomic"
"time"
db "upper.io/db.v3"
"upper.io/db.v3/internal/cache"
"upper.io/db.v3/internal/sqladapter/compat"
"upper.io/db.v3/internal/sqladapter/exql"
"upper.io/db.v3/lib/sqlbuilder"
)
var (
lastSessID uint64
lastTxID uint64
)
// hasCleanUp is implemented by structs that have a clean up routine that needs
// to be called before Close().
type hasCleanUp interface {
CleanUp() error
}
// hasStatementExec allows the adapter to have its own exec statement.
type hasStatementExec interface {
StatementExec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
}
type hasConvertValues interface {
ConvertValues(values []interface{}) []interface{}
}
// Database represents a SQL database.
type Database interface {
PartialDatabase
BaseDatabase
}
// PartialDatabase defines methods to be implemented by SQL database adapters.
type PartialDatabase interface {
sqlbuilder.SQLBuilder
// Collections returns a list of non-system tables from the database.
Collections() ([]string, error)
// Open opens a new connection
Open(db.ConnectionURL) error
// TableExists returns an error if the given table does not exist.
TableExists(name string) error
// LookupName returns the name of the database.
LookupName() (string, error)
// PrimaryKeys returns all primary keys on the table.
PrimaryKeys(name string) ([]string, error)
// NewCollection allocates a new collection by name.
NewCollection(name string) db.Collection
// CompileStatement transforms an internal statement into a format
// database/sql can understand.
CompileStatement(stmt *exql.Statement, args []interface{}) (string, []interface{})
// ConnectionURL returns the database's connection URL, if any.
ConnectionURL() db.ConnectionURL
// Err wraps specific database errors (given in string form) and transforms them
// into error values.
Err(in error) (out error)
// NewDatabaseTx begins a transaction block and returns a new
// session backed by it.
NewDatabaseTx(ctx context.Context) (DatabaseTx, error)
}
// BaseDatabase provides logic for methods that can be shared across all SQL
// adapters.
type BaseDatabase interface {
db.Settings
// Name returns the name of the database.
Name() string
// Close closes the database session
Close() error
// Ping checks if the database server is reachable.
Ping() error
// ClearCache clears all caches the session is using
ClearCache()
// Collection returns a new collection.
Collection(string) db.Collection
// Driver returns the underlying driver the session is using
Driver() interface{}
// WaitForConnection attempts to run the given connection function a fixed
// number of times before failing.
WaitForConnection(func() error) error
// BindSession sets the *sql.DB the session will use.
BindSession(*sql.DB) error
// Session returns the *sql.DB the session is using.
Session() *sql.DB
// BindTx binds a transaction to the current session.
BindTx(context.Context, *sql.Tx) error
// Returns the current transaction the session is using.
Transaction() BaseTx
// NewClone clones the database using the given PartialDatabase as base.
NewClone(PartialDatabase, bool) (BaseDatabase, error)
// Context returns the default context the session is using.
Context() context.Context
// SetContext sets a default context for the session.
SetContext(context.Context)
// TxOptions returns the default TxOptions for new transactions in the
// session.
TxOptions() *sql.TxOptions
// SetTxOptions sets default TxOptions for the session.
SetTxOptions(txOptions sql.TxOptions)
}
// NewBaseDatabase provides a BaseDatabase given a PartialDatabase
func NewBaseDatabase(p PartialDatabase) BaseDatabase {
d := &database{
Settings: db.NewSettings(),
PartialDatabase: p,
cachedCollections: cache.NewCache(),
cachedStatements: cache.NewCache(),
}
return d
}
// database is the actual implementation of Database and joins methods from
// BaseDatabase and PartialDatabase
type database struct {
PartialDatabase
db.Settings
lookupNameOnce sync.Once
name string
mu sync.Mutex // guards ctx, txOptions
ctx context.Context
txOptions *sql.TxOptions
sessMu sync.Mutex // guards sess, baseTx
sess *sql.DB
baseTx BaseTx
sessID uint64
txID uint64
cacheMu sync.Mutex // guards cachedStatements and cachedCollections
cachedStatements *cache.Cache
cachedCollections *cache.Cache
template *exql.Template
}
var (
_ = db.Database(&database{})
)
// Session returns the underlying *sql.DB
func (d *database) Session() *sql.DB {
return d.sess
}
// SetContext sets the session's default context.
func (d *database) SetContext(ctx context.Context) {
d.mu.Lock()
d.ctx = ctx
d.mu.Unlock()
}
// Context returns the session's default context.
func (d *database) Context() context.Context {
d.mu.Lock()
defer d.mu.Unlock()
if d.ctx == nil {
return context.Background()
}
return d.ctx
}
// SetTxOptions sets the session's default TxOptions.
func (d *database) SetTxOptions(txOptions sql.TxOptions) {
d.mu.Lock()
d.txOptions = &txOptions
d.mu.Unlock()
}
// TxOptions returns the session's default TxOptions.
func (d *database) TxOptions() *sql.TxOptions {
d.mu.Lock()
defer d.mu.Unlock()
if d.txOptions == nil {
return nil
}
return d.txOptions
}
// BindTx binds a *sql.Tx into *database
func (d *database) BindTx(ctx context.Context, t *sql.Tx) error {
d.sessMu.Lock()
defer d.sessMu.Unlock()
d.baseTx = newBaseTx(t)
if err := d.Ping(); err != nil {
return err
}
d.SetContext(ctx)
d.txID = newBaseTxID()
return nil
}
// Tx returns a BaseTx, which, if not nil, means that this session is within a
// transaction
func (d *database) Transaction() BaseTx {
return d.baseTx
}
// Name returns the database named
func (d *database) Name() string {
d.lookupNameOnce.Do(func() {
if d.name == "" {
d.name, _ = d.PartialDatabase.LookupName()
}
})
return d.name
}
// BindSession binds a *sql.DB into *database
func (d *database) BindSession(sess *sql.DB) error {
d.sessMu.Lock()
d.sess = sess
d.sessMu.Unlock()
if err := d.Ping(); err != nil {
return err
}
d.sessID = newSessionID()
name, err := d.PartialDatabase.LookupName()
if err != nil {
return err
}
d.name = name
return nil
}
// Ping checks whether a connection to the database is still alive by pinging
// it
func (d *database) Ping() error {
if d.sess != nil {
return d.sess.Ping()
}
return nil
}
// SetConnMaxLifetime sets the maximum amount of time a connection may be
// reused.
func (d *database) SetConnMaxLifetime(t time.Duration) {
d.Settings.SetConnMaxLifetime(t)
if sess := d.Session(); sess != nil {
sess.SetConnMaxLifetime(d.Settings.ConnMaxLifetime())
}
}
// SetMaxIdleConns sets the maximum number of connections in the idle
// connection pool.
func (d *database) SetMaxIdleConns(n int) {
d.Settings.SetMaxIdleConns(n)
if sess := d.Session(); sess != nil {
sess.SetMaxIdleConns(d.MaxIdleConns())
}
}
// SetMaxOpenConns sets the maximum number of open connections to the
// database.
func (d *database) SetMaxOpenConns(n int) {
d.Settings.SetMaxOpenConns(n)
if sess := d.Session(); sess != nil {
sess.SetMaxOpenConns(d.MaxOpenConns())
}
}
// ClearCache removes all caches.
func (d *database) ClearCache() {
d.cacheMu.Lock()
defer d.cacheMu.Unlock()
d.cachedCollections.Clear()
d.cachedStatements.Clear()
if d.template != nil {
d.template.Cache.Clear()
}
}
// NewClone binds a clone that is linked to the current
// session. This is commonly done before creating a transaction
// session.
func (d *database) NewClone(p PartialDatabase, checkConn bool) (BaseDatabase, error) {
nd := NewBaseDatabase(p).(*database)
nd.name = d.name
nd.sess = d.sess
if checkConn {
if err := nd.Ping(); err != nil {
// Retry once if ping fails.
return d.NewClone(p, false)
}
}
nd.sessID = newSessionID()
// New transaction should inherit parent settings
copySettings(d, nd)
return nd, nil
}
// Close terminates the current database session
func (d *database) Close() error {
defer func() {
d.sessMu.Lock()
d.sess = nil
d.baseTx = nil
d.sessMu.Unlock()
}()
if d.sess == nil {
return nil
}
d.cachedCollections.Clear()
d.cachedStatements.Clear() // Closes prepared statements as well.
tx := d.Transaction()
if tx == nil {
if cleaner, ok := d.PartialDatabase.(hasCleanUp); ok {
if err := cleaner.CleanUp(); err != nil {
return err
}
}
// Not within a transaction.
return d.sess.Close()
}
if !tx.Committed() {
_ = tx.Rollback()
}
return nil
}
// Collection returns a db.Collection given a name. Results are cached.
func (d *database) Collection(name string) db.Collection {
d.cacheMu.Lock()
defer d.cacheMu.Unlock()
h := cache.String(name)
ccol, ok := d.cachedCollections.ReadRaw(h)
if ok {
return ccol.(db.Collection)
}
col := d.PartialDatabase.NewCollection(name)
d.cachedCollections.Write(h, col)
return col
}
// StatementPrepare creates a prepared statement.
func (d *database) StatementPrepare(ctx context.Context, stmt *exql.Statement) (sqlStmt *sql.Stmt, err error) {
var query string
if d.Settings.LoggingEnabled() {
defer func(start time.Time) {
d.Logger().Log(&db.QueryStatus{
TxID: d.txID,
SessID: d.sessID,
Query: query,
Err: err,
Start: start,
End: time.Now(),
Context: ctx,
})
}(time.Now())
}
tx := d.Transaction()
query, _ = d.compileStatement(stmt, nil)
if tx != nil {
sqlStmt, err = compat.PrepareContext(tx.(*baseTx), ctx, query)
return
}
sqlStmt, err = compat.PrepareContext(d.sess, ctx, query)
return
}
// ConvertValues converts native values into driver specific values.
func (d *database) ConvertValues(values []interface{}) []interface{} {
if converter, ok := d.PartialDatabase.(hasConvertValues); ok {
return converter.ConvertValues(values)
}
return values
}
// StatementExec compiles and executes a statement that does not return any
// rows.
func (d *database) StatementExec(ctx context.Context, stmt *exql.Statement, args ...interface{}) (res sql.Result, err error) {
var query string
if d.Settings.LoggingEnabled() {
defer func(start time.Time) {
status := db.QueryStatus{
TxID: d.txID,
SessID: d.sessID,
Query: query,
Args: args,
Err: err,
Start: start,
End: time.Now(),
Context: ctx,
}
if res != nil {
if rowsAffected, err := res.RowsAffected(); err == nil {
status.RowsAffected = &rowsAffected
}
if lastInsertID, err := res.LastInsertId(); err == nil {
status.LastInsertID = &lastInsertID
}
}
d.Logger().Log(&status)
}(time.Now())
}
if execer, ok := d.PartialDatabase.(hasStatementExec); ok {
query, args = d.compileStatement(stmt, args)
res, err = execer.StatementExec(ctx, query, args...)
return
}
tx := d.Transaction()
if d.Settings.PreparedStatementCacheEnabled() && tx == nil {
var p *Stmt
if p, query, args, err = d.prepareStatement(ctx, stmt, args); err != nil {
return nil, err
}
defer p.Close()
res, err = compat.PreparedExecContext(p, ctx, args)
return
}
query, args = d.compileStatement(stmt, args)
if tx != nil {
res, err = compat.ExecContext(tx.(*baseTx), ctx, query, args)
return
}
res, err = compat.ExecContext(d.sess, ctx, query, args)
return
}
// StatementQuery compiles and executes a statement that returns rows.
func (d *database) StatementQuery(ctx context.Context, stmt *exql.Statement, args ...interface{}) (rows *sql.Rows, err error) {
var query string
if d.Settings.LoggingEnabled() {
defer func(start time.Time) {
d.Logger().Log(&db.QueryStatus{
TxID: d.txID,
SessID: d.sessID,
Query: query,
Args: args,
Err: err,
Start: start,
End: time.Now(),
Context: ctx,
})
}(time.Now())
}
tx := d.Transaction()
if d.Settings.PreparedStatementCacheEnabled() && tx == nil {
var p *Stmt
if p, query, args, err = d.prepareStatement(ctx, stmt, args); err != nil {
return nil, err
}
defer p.Close()
rows, err = compat.PreparedQueryContext(p, ctx, args)
return
}
query, args = d.compileStatement(stmt, args)
if tx != nil {
rows, err = compat.QueryContext(tx.(*baseTx), ctx, query, args)
return
}
rows, err = compat.QueryContext(d.sess, ctx, query, args)
return
}
// StatementQueryRow compiles and executes a statement that returns at most one
// row.
func (d *database) StatementQueryRow(ctx context.Context, stmt *exql.Statement, args ...interface{}) (row *sql.Row, err error) {
var query string
if d.Settings.LoggingEnabled() {
defer func(start time.Time) {
d.Logger().Log(&db.QueryStatus{
TxID: d.txID,
SessID: d.sessID,
Query: query,
Args: args,
Err: err,
Start: start,
End: time.Now(),
Context: ctx,
})
}(time.Now())
}
tx := d.Transaction()
if d.Settings.PreparedStatementCacheEnabled() && tx == nil {
var p *Stmt
if p, query, args, err = d.prepareStatement(ctx, stmt, args); err != nil {
return nil, err
}
defer p.Close()
row = compat.PreparedQueryRowContext(p, ctx, args)
return
}
query, args = d.compileStatement(stmt, args)
if tx != nil {
row = compat.QueryRowContext(tx.(*baseTx), ctx, query, args)
return
}
row = compat.QueryRowContext(d.sess, ctx, query, args)
return
}
// Driver returns the underlying *sql.DB or *sql.Tx instance.
func (d *database) Driver() interface{} {
if tx := d.Transaction(); tx != nil {
// A transaction
return tx.(*baseTx).Tx
}
return d.sess
}
// compileStatement compiles the given statement into a string.
func (d *database) compileStatement(stmt *exql.Statement, args []interface{}) (string, []interface{}) {
if converter, ok := d.PartialDatabase.(hasConvertValues); ok {
args = converter.ConvertValues(args)
}
return d.PartialDatabase.CompileStatement(stmt, args)
}
// prepareStatement compiles a query and tries to use previously generated
// statement.
func (d *database) prepareStatement(ctx context.Context, stmt *exql.Statement, args []interface{}) (*Stmt, string, []interface{}, error) {
d.sessMu.Lock()
defer d.sessMu.Unlock()
sess, tx := d.sess, d.Transaction()
if sess == nil && tx == nil {
return nil, "", nil, db.ErrNotConnected
}
pc, ok := d.cachedStatements.ReadRaw(stmt)
if ok {
// The statement was cached.
ps, err := pc.(*Stmt).Open()
if err == nil {
_, args = d.compileStatement(stmt, args)
return ps, ps.query, args, nil
}
}
query, args := d.compileStatement(stmt, args)
sqlStmt, err := func(query *string) (*sql.Stmt, error) {
if tx != nil {
return compat.PrepareContext(tx.(*baseTx), ctx, *query)
}
return compat.PrepareContext(sess, ctx, *query)
}(&query)
if err != nil {
return nil, "", nil, err
}
p, err := NewStatement(sqlStmt, query).Open()
if err != nil {
return nil, query, args, err
}
d.cachedStatements.Write(stmt, p)
return p, p.query, args, nil
}
var waitForConnMu sync.Mutex
// WaitForConnection tries to execute the given connectFn function, if
// connectFn returns an error, then WaitForConnection will keep trying until
// connectFn returns nil. Maximum waiting time is 5s after having acquired the
// lock.
func (d *database) WaitForConnection(connectFn func() error) error {
// This lock ensures first-come, first-served and prevents opening too many
// file descriptors.
waitForConnMu.Lock()
defer waitForConnMu.Unlock()
// Minimum waiting time.
waitTime := time.Millisecond * 10
// Waitig 5 seconds for a successful connection.
for timeStart := time.Now(); time.Since(timeStart) < time.Second*5; {
err := connectFn()
if err == nil {
return nil // Connected!
}
// Only attempt to reconnect if the error is too many clients.
if d.PartialDatabase.Err(err) == db.ErrTooManyClients {
// Sleep and try again if, and only if, the server replied with a "too
// many clients" error.
time.Sleep(waitTime)
if waitTime < time.Millisecond*500 {
// Wait a bit more next time.
waitTime = waitTime * 2
}
continue
}
// Return any other error immediately.
return err
}
return db.ErrGivingUpTryingToConnect
}
// ReplaceWithDollarSign turns a SQL statament with '?' placeholders into
// dollar placeholders, like $1, $2, ..., $n
func ReplaceWithDollarSign(in string) string {
buf := []byte(in)
out := make([]byte, 0, len(buf))
i, j, k, t := 0, 1, 0, len(buf)
for i < t {
if buf[i] == '?' {
out = append(out, buf[k:i]...)
k = i + 1
if k < t && buf[k] == '?' {
i = k
} else {
out = append(out, []byte("$"+strconv.Itoa(j))...)
j++
}
}
i++
}
out = append(out, buf[k:i]...)
return string(out)
}
func copySettings(from BaseDatabase, into BaseDatabase) {
into.SetLogging(from.LoggingEnabled())
into.SetLogger(from.Logger())
into.SetPreparedStatementCache(from.PreparedStatementCacheEnabled())
into.SetConnMaxLifetime(from.ConnMaxLifetime())
into.SetMaxIdleConns(from.MaxIdleConns())
into.SetMaxOpenConns(from.MaxOpenConns())
txOptions := from.TxOptions()
if txOptions != nil {
into.SetTxOptions(*txOptions)
}
}
func newSessionID() uint64 {
if atomic.LoadUint64(&lastSessID) == math.MaxUint64 {
atomic.StoreUint64(&lastSessID, 0)
return 0
}
return atomic.AddUint64(&lastSessID, 1)
}
func newBaseTxID() uint64 {
if atomic.LoadUint64(&lastTxID) == math.MaxUint64 {
atomic.StoreUint64(&lastTxID, 0)
return 0
}
return atomic.AddUint64(&lastTxID, 1)
}