-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlite.go
1268 lines (989 loc) · 28.4 KB
/
sqlite.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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package sqlite
import (
"context"
"database/sql"
"database/sql/driver"
"embed"
"errors"
"expvar"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/mattn/go-sqlite3"
"github.com/polyscone/tofu/app"
"github.com/polyscone/tofu/errsx"
"github.com/polyscone/tofu/uuid"
)
//go:embed "all:migrations"
var migrations embed.FS
const driverName = "sqlite3_custom"
func init() {
sql.Register(driverName, &sqlite3.SQLiteDriver{
ConnectHook: func(conn *sqlite3.SQLiteConn) error {
_, err := conn.Exec(`
PRAGMA encoding = 'UTF-8';
PRAGMA busy_timeout = 30000;
PRAGMA temp_store = MEMORY;
PRAGMA cache_size = 50000;
PRAGMA journal_mode = WAL;
PRAGMA foreign_keys = ON;
PRAGMA secure_delete = ON;
PRAGMA synchronous = NORMAL;
`, nil)
return err
},
})
}
type Kind string
const (
KindFile Kind = "file"
KindMemory Kind = "memory"
)
var databases = struct {
mu sync.RWMutex
data map[string]*DB
}{data: make(map[string]*DB)}
func Open(ctx context.Context, kind Kind, filename string, metrics *expvar.Map) (*DB, error) {
var dsn string
switch kind {
case KindFile:
dir := filepath.Dir(filename)
if err := os.MkdirAll(dir, 0755); err != nil {
return nil, fmt.Errorf("make directory: %w", err)
}
dsn = filename
case KindMemory:
// Because Go implements a connection pool it means that when the
// standard library opens a new connection any in-memory tables etc.
// will look like they've been lost because they were created on a
// different connection from the same pool
//
// To get around this it is possible to use a DSN like:
//
// file::memory:?cache=shared
//
// References:
// - https://www.sqlite.org/sharedcache.html#shared_cache_and_in_memory_databases
// - https://www.sqlite.org/inmemorydb.html#sharedmemdb
//
// Using file::memory: with a shared cache would allow each connection
// in the connection pool to connect to the same in-memory database
// and share a cache, rather than having their own private one each
//
// To allow for many different in-memory connections we can further
// expand this to take a file name with a mode parameter instead:
//
// file:<name>?cache=shared&mode=memory
//
// All of this together prevents different connections to the same
// in-memory database from seeing different states, and still allows
// for unique in-memory databases when required
dsn = "file:" + filename + "?cache=shared&mode=memory"
default:
panic(fmt.Sprintf("unknown sqlite connection kind %q", kind))
}
databases.mu.RLock()
if db, ok := databases.data[dsn]; ok {
databases.mu.RUnlock()
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
if err := db.PingContext(ctx); err == nil {
return db, nil
}
}
databases.mu.RUnlock()
databases.mu.Lock()
defer databases.mu.Unlock()
// We check for an existing connection pool here because another goroutine
// could have already connected whilst other locks were waiting
if db, ok := databases.data[dsn]; ok {
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
// It's possible that we find an existing connection pool that failed
// to ping, in which case we only want to return it if we know the
// connection is still alive, so we try to ping again to be sure
if err := db.PingContext(ctx); err == nil {
return db, nil
}
// If we reach this point then it's because we've failed to ping the
// database a couple of times and we need to replace the connection pool
// so we attempt to close before replacing
db.Close()
}
sqlDB, err := sql.Open(driverName, dsn)
if err != nil {
return nil, repoerr(err)
}
db := &DB{
DB: sqlDB,
metrics: metrics,
}
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
if err := db.PingContext(ctx); err != nil {
return nil, fmt.Errorf("ping: %w", repoerr(err))
}
databases.data[dsn] = db
return db, nil
}
func OpenInMemoryTestDatabase(ctx context.Context) *DB {
randomName := errsx.Must(uuid.NewV4()).String() + ".sqlite"
return errsx.Must(Open(ctx, KindMemory, randomName, nil))
}
func migrate(ctx context.Context, tx *sql.Tx, name string, migrations []string) error {
if len(migrations) == 0 {
return nil
}
stmt := `
CREATE TABLE IF NOT EXISTS _migrations (
name TEXT PRIMARY KEY NOT NULL,
version INTEGER NOT NULL,
created_at DATETIME NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', CURRENT_TIMESTAMP)),
updated_at DATETIME
);
INSERT OR IGNORE INTO _migrations (name, version) VALUES (:name, 0);
`
args := []any{sql.Named("name", name)}
if _, err := tx.ExecContext(ctx, stmt, args...); err != nil {
return err
}
var version int
stmt = "SELECT version FROM _migrations WHERE name = :name;"
args = []any{sql.Named("name", name)}
if err := tx.QueryRowContext(ctx, stmt, args...).Scan(&version); err != nil {
return err
}
if version < 0 {
return fmt.Errorf("want current migration to be version 0 or more; got %v", version)
}
migration := version
nm := len(migrations)
// If the number of migration strings is less than the version then we must have
// lost some migrations and the data cannot be trusted
if nm < version {
return fmt.Errorf("want at least %v migration strings; got %v", version, nm)
}
// If the version is the same as the number of migration strings then we must be up to date
if nm == version {
return nil
}
for i, stmt := range migrations {
if i < version {
continue
}
// If the migration file is empty then don't waste the
// time trying to execute a query
if stmt = strings.TrimSpace(stmt); stmt == "" {
continue
}
if _, err := tx.ExecContext(ctx, stmt); err != nil {
return err
}
migration++
}
// If the migration number is greater than the starting version then
// that means we must have executed some migration strings so we
// should attempt to set the migration version to the new number
if migration > version {
stmt := `
UPDATE _migrations SET
version = :version,
updated_at = :updated_at
WHERE name = :name;
`
args := []any{
sql.Named("version", migration),
sql.Named("updated_at", Time(time.Now().UTC())),
sql.Named("name", name),
}
if _, err := tx.ExecContext(ctx, stmt, args...); err != nil {
return err
}
}
return nil
}
func migrateFS(ctx context.Context, db *sql.DB, name string, fsys fs.FS) error {
// We get a connection from the pool directly here so we can make
// sure that pragmas run on this connection will be in effect for the
// transaction we use for migrations
//
// If we use sql.DB.BeginTx directly then the connection used for the
// transaction could end up being a different one from the pool
conn, err := db.Conn(ctx)
if err != nil {
return fmt.Errorf("begin tx: %w", err)
}
defer conn.Close()
// Pragmas need to be set before the transaction starts, which is why
// we do it on the connection here
if _, err := conn.ExecContext(ctx, "PRAGMA foreign_keys = OFF;"); err != nil {
return err
}
tx, err := conn.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin tx: %w", err)
}
defer tx.Rollback()
files, err := fs.ReadDir(fsys, ".")
if err != nil {
return fmt.Errorf("read migration directory: %w", err)
}
queries := make([]string, len(files))
for i, f := range files {
filename := f.Name()
if f.IsDir() {
return fmt.Errorf("want file; got directory %q", filename)
}
if filename[:4] != fmt.Sprintf("%04d", i+1) {
return fmt.Errorf("want file beginning with %04d; got %q", i+1, filename)
}
b, err := fs.ReadFile(fsys, filename)
if err != nil {
return fmt.Errorf("read migration file: %w", err)
}
queries[i] = string(b)
}
if err := migrate(ctx, tx, name, queries); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("tx commit: %w", err)
}
// Since pragmas are set outside of the transaction we need to
// make sure we revert the changes here
if _, err := conn.ExecContext(ctx, "PRAGMA foreign_keys = ON;"); err != nil {
return err
}
return nil
}
type recordKind byte
const (
recordKindUnknown recordKind = iota
recordKindRead
recordKindWrite
)
func recordQuery(metrics *expvar.Map, kind recordKind) func() {
if metrics == nil {
return func() {}
}
now := time.Now()
return func() {
since := time.Since(now).Nanoseconds()
switch kind {
case recordKindRead:
metrics.Add("totalReads", 1)
metrics.Add("totalReadTime", since)
case recordKindWrite:
metrics.Add("totalWrites", 1)
metrics.Add("totalWriteTime", since)
}
metrics.Add("totalQueries", 1)
metrics.Add("totalQueryTime", since)
}
}
func repoerr(err error) error {
if err == nil {
return nil
}
if errors.Is(err, sql.ErrNoRows) {
return app.ErrNotFound
}
msg := strings.ToLower(err.Error())
switch {
case strings.Contains(msg, "unique constraint failed"):
return app.ErrConflict
case strings.Contains(msg, "login error"):
return fmt.Errorf("%w: %w", app.ErrRepoLogin, err)
}
return err
}
func whereSQL(where []string) string {
if len(where) == 0 {
return ""
}
return "WHERE (" + strings.Join(where, ") AND (") + ")"
}
func orderBySQL(sorts []string) string {
if len(sorts) == 0 {
return ""
}
return "ORDER BY " + strings.Join(sorts, ", ")
}
func pageLimitOffset(page, size int) (int, int) {
limit := size
offset := (page - 1) * size
return limit, offset
}
func limitOffsetSQL(limit, offset int) string {
switch {
case limit > 0 && offset > 0:
return fmt.Sprintf("LIMIT %v offset %v", limit, offset)
case limit > 0:
return fmt.Sprintf("LIMIT %v", limit)
case offset > 0:
return fmt.Sprintf("OFFSET %v", offset)
}
return ""
}
func inSQL[T any](args []T) (string, []any) {
placeholders := strings.Join(strings.Split(strings.Repeat("?", len(args)), ""), ", ")
values := make([]any, len(args))
for i := 0; i < len(values); i++ {
values[i] = args[i]
}
return placeholders, values
}
const RFC3339NanoZero = "2006-01-02T15:04:05.000000000Z07:00"
type Time time.Time
func (t Time) String() string {
return time.Time(t).String()
}
func (t *Time) Scan(value any) error {
switch value := value.(type) {
case nil:
*t = Time(time.Time{})
case time.Time:
*t = Time(value)
case *time.Time:
*t = Time(*value)
case string:
parsed, err := time.Parse(RFC3339NanoZero, value)
if err != nil {
return fmt.Errorf("parse RFC3339 nano with trailing zeros: %w", err)
}
*t = Time(parsed)
default:
return fmt.Errorf("%T: cannot scan to time.Time: %T", Time{}, value)
}
return nil
}
func (t Time) Value() (driver.Value, error) {
return time.Time(t).Format(RFC3339NanoZero), nil
}
type NullTime time.Time
func (t NullTime) String() string {
return time.Time(t).String()
}
func (t *NullTime) Scan(value any) error {
switch value := value.(type) {
case nil:
*t = NullTime(time.Time{})
case time.Time:
*t = NullTime(value)
case *time.Time:
*t = NullTime(*value)
case string:
parsed, err := time.Parse(RFC3339NanoZero, value)
if err != nil {
return fmt.Errorf("parse RFC3339 nano with trailing zeros: %w", err)
}
*t = NullTime(parsed)
default:
return fmt.Errorf("%T: cannot scan to time.Time: %T", NullTime{}, value)
}
return nil
}
func (t NullTime) Value() (driver.Value, error) {
if time.Time(t).IsZero() {
return nil, nil
}
return time.Time(t).Format(RFC3339NanoZero), nil
}
type Duration time.Duration
func (d Duration) String() string {
return time.Duration(d).String()
}
func (d *Duration) Scan(value any) error {
switch value := value.(type) {
case nil:
*d = Duration(0)
case time.Duration:
*d = Duration(value)
case *time.Duration:
*d = Duration(*value)
case int64:
*d = Duration(value)
case string:
parsed, err := time.ParseDuration(value)
if err != nil {
return fmt.Errorf("parse duration: %w", err)
}
*d = Duration(parsed)
default:
return fmt.Errorf("%T: cannot scan to time.Duration: %T", Duration(0), value)
}
return nil
}
func (d Duration) Value() (driver.Value, error) {
return time.Duration(d).String(), nil
}
type NullDuration time.Duration
func (d NullDuration) String() string {
return time.Duration(d).String()
}
func (d *NullDuration) Scan(value any) error {
switch value := value.(type) {
case nil:
*d = NullDuration(0)
case time.Duration:
*d = NullDuration(value)
case *time.Duration:
*d = NullDuration(*value)
case int64:
*d = NullDuration(value)
case string:
parsed, err := time.ParseDuration(value)
if err != nil {
return fmt.Errorf("parse duration: %w", err)
}
*d = NullDuration(parsed)
default:
return fmt.Errorf("%T: cannot scan to time.Duration: %T", NullDuration(0), value)
}
return nil
}
func (d NullDuration) Value() (driver.Value, error) {
if d == 0 {
return nil, nil
}
return time.Duration(d).String(), nil
}
func validateArg(arg any) error {
switch arg := arg.(type) {
case time.Time, *time.Time, **time.Time,
sql.NullTime, *sql.NullTime, **sql.NullTime,
sql.Null[time.Time], *sql.Null[time.Time], **sql.Null[time.Time]:
return fmt.Errorf(
"cannot use %T as an arg; convert to one of: %T, %T, %T, or %T instead",
arg, Time{}, &Time{}, NullTime{}, &NullTime{},
)
case time.Duration, *time.Duration, **time.Duration:
d1 := Duration(0)
d2 := NullDuration(0)
return fmt.Errorf(
"cannot use %T as an arg; convert to one of: %T, %T, %T, or %T instead",
arg, d1, &d1, d2, &d2,
)
case sql.NamedArg:
return validateArg(arg.Value)
default:
return nil
}
}
type Conn struct {
*sql.Conn
metrics *expvar.Map
}
func (c *Conn) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
tx, err := c.Conn.BeginTx(ctx, opts)
if err != nil {
return nil, err
}
if c.metrics != nil {
c.metrics.Add("totalTransactionsBegun", 1)
}
_tx := &Tx{Tx: tx, ctx: ctx, now: time.Now(), metrics: c.metrics}
go _tx.awaitDone()
return _tx, nil
}
// BeginImmediateTx starts an immediate transaction with "BEGIN IMMEDIATE".
//
// This is a workaround for Go's database/sql package not providing a way to set
// the transaction type per connection.
//
// References:
// - https://github.com/golang/go/issues/19981
// - https://github.com/mattn/go-sqlite3/issues/400
func (c *Conn) BeginImmediateTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
tx, err := c.BeginTx(ctx, opts)
if err != nil {
return nil, err
}
// The returned transaction is a connection from a connection pool, so we
// can rollback the (by default) "DEFERRED" transaction and start a new
// "IMMEDIATE" one
if _, err := tx.ExecContext(ctx, "ROLLBACK; BEGIN IMMEDIATE"); err != nil {
return nil, err
}
if c.metrics != nil {
c.metrics.Add("totalTransactionsBegun", 1)
}
return tx, nil
}
// BeginExclusiveTx starts an exclusive transaction with "BEGIN EXCLUSIVE".
//
// This is a workaround for Go's database/sql package not providing a way to set
// the transaction type per connection.
//
// References:
// - https://github.com/golang/go/issues/19981
// - https://github.com/mattn/go-sqlite3/issues/400
func (c *Conn) BeginExclusiveTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
tx, err := c.BeginTx(ctx, opts)
if err != nil {
return nil, err
}
// The returned transaction is a connection from a connection pool, so we
// can rollback the (by default) "DEFERRED" transaction and start a new
// "EXCLUSIVE" one
if _, err := tx.ExecContext(ctx, "ROLLBACK; BEGIN EXCLUSIVE"); err != nil {
return nil, err
}
if c.metrics != nil {
c.metrics.Add("totalTransactionsBegun", 1)
}
return tx, nil
}
func (c *Conn) PrepareContext(ctx context.Context, query string) (*Stmt, error) {
stmt, err := c.Conn.PrepareContext(ctx, query)
if err != nil {
return nil, err
}
return &Stmt{Stmt: stmt, metrics: c.metrics}, nil
}
func (c *Conn) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) {
defer recordQuery(c.metrics, recordKindWrite)()
for _, arg := range args {
if err := validateArg(arg); err != nil {
return nil, err
}
}
res, err := c.Conn.ExecContext(ctx, query, args...)
if err != nil {
return res, repoerr(err)
}
return res, nil
}
func (c *Conn) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error) {
defer recordQuery(c.metrics, recordKindRead)()
for _, arg := range args {
if err := validateArg(arg); err != nil {
return nil, err
}
}
_rows, err := c.Conn.QueryContext(ctx, query, args...)
if err != nil {
return nil, repoerr(err)
}
rows := &Rows{Rows: _rows, metrics: c.metrics}
rows.record()
return rows, nil
}
func (c *Conn) QueryRowContext(ctx context.Context, query string, args ...any) *Row {
defer recordQuery(c.metrics, recordKindRead)()
for _, arg := range args {
if err := validateArg(arg); err != nil {
return &Row{err: err}
}
}
_row := c.Conn.QueryRowContext(ctx, query, args...)
row := &Row{Row: _row, metrics: c.metrics}
row.record()
return row
}
type DB struct {
*sql.DB
metrics *expvar.Map
}
func (db *DB) Conn(ctx context.Context) (*Conn, error) {
conn, err := db.DB.Conn(ctx)
if err != nil {
return nil, err
}
return &Conn{Conn: conn, metrics: db.metrics}, nil
}
func (db *DB) Begin() (*Tx, error) {
return db.BeginTx(context.Background(), nil)
}
func (db *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
tx, err := db.DB.BeginTx(ctx, opts)
if err != nil {
return nil, err
}
if db.metrics != nil {
db.metrics.Add("totalTransactionsBegun", 1)
}
_tx := &Tx{Tx: tx, ctx: ctx, now: time.Now(), metrics: db.metrics}
go _tx.awaitDone()
return _tx, nil
}
// BeginImmediateTx starts an immediate transaction with "BEGIN IMMEDIATE".
//
// This is a workaround for Go's database/sql package not providing a way to set
// the transaction type per connection.
//
// References:
// - https://github.com/golang/go/issues/19981
// - https://github.com/mattn/go-sqlite3/issues/400
func (db *DB) BeginImmediateTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
tx, err := db.BeginTx(ctx, opts)
if err != nil {
return nil, err
}
// The returned transaction is a connection from a connection pool, so we
// can rollback the (by default) "DEFERRED" transaction and start a new
// "IMMEDIATE" one
if _, err := tx.ExecContext(ctx, "ROLLBACK; BEGIN IMMEDIATE"); err != nil {
return nil, err
}
if db.metrics != nil {
db.metrics.Add("totalTransactionsBegun", 1)
}
return tx, nil
}
// BeginExclusiveTx starts an exclusive transaction with "BEGIN EXCLUSIVE".
//
// This is a workaround for Go's database/sql package not providing a way to set
// the transaction type per connection.
//
// References:
// - https://github.com/golang/go/issues/19981
// - https://github.com/mattn/go-sqlite3/issues/400
func (db *DB) BeginExclusiveTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
tx, err := db.BeginTx(ctx, opts)
if err != nil {
return nil, err
}
// The returned transaction is a connection from a connection pool, so we
// can rollback the (by default) "DEFERRED" transaction and start a new
// "EXCLUSIVE" one
if _, err := tx.ExecContext(ctx, "ROLLBACK; BEGIN EXCLUSIVE"); err != nil {
return nil, err
}
if db.metrics != nil {
db.metrics.Add("totalTransactionsBegun", 1)
}
return tx, nil
}
func (db *DB) Prepare(query string) (*Stmt, error) {
return db.PrepareContext(context.Background(), query)
}
func (db *DB) PrepareContext(ctx context.Context, query string) (*Stmt, error) {
stmt, err := db.DB.PrepareContext(ctx, query)
if err != nil {
return nil, err
}
return &Stmt{Stmt: stmt, metrics: db.metrics}, nil
}
func (db *DB) Exec(query string, args ...any) (sql.Result, error) {
return db.ExecContext(context.Background(), query, args...)
}
func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) {
defer recordQuery(db.metrics, recordKindWrite)()
for _, arg := range args {
if err := validateArg(arg); err != nil {
return nil, err
}
}
res, err := db.DB.ExecContext(ctx, query, args...)
if err != nil {
return res, repoerr(err)
}
return res, nil
}
func (db *DB) Query(query string, args ...any) (*Rows, error) {
return db.QueryContext(context.Background(), query, args...)
}
func (db *DB) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error) {
defer recordQuery(db.metrics, recordKindRead)()
for _, arg := range args {
if err := validateArg(arg); err != nil {
return nil, err
}
}
_rows, err := db.DB.QueryContext(ctx, query, args...)
if err != nil {
return nil, repoerr(err)
}
rows := &Rows{Rows: _rows, metrics: db.metrics}
rows.record()
return rows, nil
}
func (db *DB) QueryRow(query string, args ...any) *Row {
return db.QueryRowContext(context.Background(), query, args...)
}
func (db *DB) QueryRowContext(ctx context.Context, query string, args ...any) *Row {
defer recordQuery(db.metrics, recordKindRead)()
for _, arg := range args {
if err := validateArg(arg); err != nil {
return &Row{err: err}
}
}
_row := db.DB.QueryRowContext(ctx, query, args...)
row := &Row{Row: _row, metrics: db.metrics}
row.record()
return row
}
type Stmt struct {
*sql.Stmt
metrics *expvar.Map
}
func (stmt *Stmt) Exec(args ...any) (sql.Result, error) {
return stmt.ExecContext(context.Background(), args...)
}
func (stmt *Stmt) ExecContext(ctx context.Context, args ...any) (sql.Result, error) {
defer recordQuery(stmt.metrics, recordKindWrite)()
for _, arg := range args {
if err := validateArg(arg); err != nil {
return nil, err
}
}
res, err := stmt.Stmt.ExecContext(ctx, args...)
if err != nil {
return res, repoerr(err)
}
return res, nil
}
func (stmt *Stmt) Query(args ...any) (*Rows, error) {
return stmt.QueryContext(context.Background(), args...)
}
func (stmt *Stmt) QueryContext(ctx context.Context, args ...any) (*Rows, error) {
defer recordQuery(stmt.metrics, recordKindRead)()
for _, arg := range args {
if err := validateArg(arg); err != nil {
return nil, err
}
}
_rows, err := stmt.Stmt.QueryContext(ctx, args...)
if err != nil {
return nil, repoerr(err)
}
rows := &Rows{Rows: _rows, metrics: stmt.metrics}
rows.record()
return rows, nil
}
func (stmt *Stmt) QueryRow(args ...any) *Row {
return stmt.QueryRowContext(context.Background(), args...)
}
func (stmt *Stmt) QueryRowContext(ctx context.Context, args ...any) *Row {
defer recordQuery(stmt.metrics, recordKindRead)()
for _, arg := range args {
if err := validateArg(arg); err != nil {
return &Row{err: err}
}
}
_row := stmt.Stmt.QueryRowContext(ctx, args...)
row := &Row{Row: _row, metrics: stmt.metrics}
row.record()
return row
}
type Tx struct {
*sql.Tx
ctx context.Context
now time.Time
metrics *expvar.Map
recorded atomic.Bool
maybeWrite bool
}