-
Notifications
You must be signed in to change notification settings - Fork 3
/
fakedb_test.go
1311 lines (1162 loc) · 31.4 KB
/
fakedb_test.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
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// package sql
package sqlrange_test
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"io"
"reflect"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
const fakeDBName = "foo"
var chrisBirthday = time.Unix(123456789, 0)
func newTestDB(t testing.TB, name string) *sql.DB {
return newTestDBConnector(t, &fakeConnector{name: fakeDBName}, name)
}
func newTestDBConnector(t testing.TB, fc *fakeConnector, name string) *sql.DB {
fc.name = fakeDBName
db := sql.OpenDB(fc)
if _, err := db.Exec("WIPE"); err != nil {
t.Fatalf("exec wipe: %v", err)
}
if name == "people" {
exec(t, db, "CREATE|people|name=string,age=int32,photo=blob,dead=bool,bdate=datetime")
exec(t, db, "INSERT|people|name=Alice,age=?,photo=APHOTO", 1)
exec(t, db, "INSERT|people|name=Bob,age=?,photo=BPHOTO", 2)
exec(t, db, "INSERT|people|name=Chris,age=?,photo=CPHOTO,bdate=?", 3, chrisBirthday)
}
if name == "magicquery" {
// Magic table name and column, known by fakedb_test.go.
exec(t, db, "CREATE|magicquery|op=string,millis=int32")
exec(t, db, "INSERT|magicquery|op=sleep,millis=10")
}
if name == "tx_status" {
// Magic table name and column, known by fakedb_test.go.
exec(t, db, "CREATE|tx_status|tx_status=string")
exec(t, db, "INSERT|tx_status|tx_status=invalid")
}
return db
}
func exec(t testing.TB, db *sql.DB, query string, args ...any) {
t.Helper()
_, err := db.Exec(query, args...)
if err != nil {
t.Fatalf("Exec of %q: %v", query, err)
}
}
// fakeDriver is a fake database that implements Go's driver.Driver
// interface, just for testing.
//
// It speaks a query language that's semantically similar to but
// syntactically different and simpler than SQL. The syntax is as
// follows:
//
// WIPE
// CREATE|<tablename>|<col>=<type>,<col>=<type>,...
// where types are: "string", [u]int{8,16,32,64}, "bool"
// INSERT|<tablename>|col=val,col2=val2,col3=?
// SELECT|<tablename>|projectcol1,projectcol2|filtercol=?,filtercol2=?
// SELECT|<tablename>|projectcol1,projectcol2|filtercol=?param1,filtercol2=?param2
//
// Any of these can be preceded by PANIC|<method>|, to cause the
// named method on fakeStmt to panic.
//
// Any of these can be proceeded by WAIT|<duration>|, to cause the
// named method on fakeStmt to sleep for the specified duration.
//
// Multiple of these can be combined when separated with a semicolon.
//
// When opening a fakeDriver's database, it starts empty with no
// tables. All tables and data are stored in memory only.
type fakeDriver struct {
mu sync.Mutex // guards 3 following fields
openCount int // conn opens
closeCount int // conn closes
waitCh chan struct{}
waitingCh chan struct{}
dbs map[string]*fakeDB
}
type fakeConnector struct {
name string
waiter func(context.Context)
closed bool
}
func (c *fakeConnector) Connect(context.Context) (driver.Conn, error) {
conn, err := fdriver.Open(c.name)
conn.(*fakeConn).waiter = c.waiter
return conn, err
}
func (c *fakeConnector) Driver() driver.Driver {
return fdriver
}
func (c *fakeConnector) Close() error {
if c.closed {
return errors.New("fakedb: connector is closed")
}
c.closed = true
return nil
}
type fakeDriverCtx struct {
fakeDriver
}
var _ driver.DriverContext = &fakeDriverCtx{}
func (cc *fakeDriverCtx) OpenConnector(name string) (driver.Connector, error) {
return &fakeConnector{name: name}, nil
}
type fakeDB struct {
name string
useRawBytes atomic.Bool
mu sync.Mutex
tables map[string]*table
badConn bool
allowAny bool
}
type fakeError struct {
Message string
Wrapped error
}
func (err fakeError) Error() string {
return err.Message
}
func (err fakeError) Unwrap() error {
return err.Wrapped
}
type table struct {
mu sync.Mutex
colname []string
coltype []string
rows []*row
}
func (t *table) columnIndex(name string) int {
for n, nname := range t.colname {
if name == nname {
return n
}
}
return -1
}
type row struct {
cols []any // must be same size as its table colname + coltype
}
type memToucher interface {
// touchMem reads & writes some memory, to help find data races.
touchMem()
}
type fakeConn struct {
db *fakeDB // where to return ourselves to
currTx *fakeTx
// Every operation writes to line to enable the race detector
// check for data races.
line int64
// Stats for tests:
mu sync.Mutex
stmtsMade int
stmtsClosed int
numPrepare int
// bad connection tests; see isBad()
bad bool
stickyBad bool
skipDirtySession bool // tests that use Conn should set this to true.
// dirtySession tests ResetSession, true if a query has executed
// until ResetSession is called.
dirtySession bool
// The waiter is called before each query. May be used in place of the "WAIT"
// directive.
waiter func(context.Context)
}
func (c *fakeConn) touchMem() {
c.line++
}
func (c *fakeConn) incrStat(v *int) {
c.mu.Lock()
*v++
c.mu.Unlock()
}
type fakeTx struct {
c *fakeConn
}
type boundCol struct {
Column string
Placeholder string
Ordinal int
}
type fakeStmt struct {
memToucher
c *fakeConn
q string // just for debugging
cmd string
table string
panic string
wait time.Duration
next *fakeStmt // used for returning multiple results.
closed bool
colName []string // used by CREATE, INSERT, SELECT (selected columns)
colType []string // used by CREATE
colValue []any // used by INSERT (mix of strings and "?" for bound params)
placeholders int // used by INSERT/SELECT: number of ? params
whereCol []boundCol // used by SELECT (all placeholders)
placeholderConverter []driver.ValueConverter // used by INSERT
}
var fdriver driver.Driver = &fakeDriver{}
func init() {
sql.Register("test", fdriver)
}
func contains(list []string, y string) bool {
for _, x := range list {
if x == y {
return true
}
}
return false
}
// hook to simulate connection failures
var hookOpenErr struct {
sync.Mutex
fn func() error
}
func setHookOpenErr(fn func() error) {
hookOpenErr.Lock()
defer hookOpenErr.Unlock()
hookOpenErr.fn = fn
}
// Supports dsn forms:
//
// <dbname>
// <dbname>;<opts> (only currently supported option is `badConn`,
// which causes driver.ErrBadConn to be returned on
// every other conn.Begin())
func (d *fakeDriver) Open(dsn string) (driver.Conn, error) {
hookOpenErr.Lock()
fn := hookOpenErr.fn
hookOpenErr.Unlock()
if fn != nil {
if err := fn(); err != nil {
return nil, err
}
}
parts := strings.Split(dsn, ";")
if len(parts) < 1 {
return nil, errors.New("fakedb: no database name")
}
name := parts[0]
db := d.getDB(name)
d.mu.Lock()
d.openCount++
d.mu.Unlock()
conn := &fakeConn{db: db}
if len(parts) >= 2 && parts[1] == "badConn" {
conn.bad = true
}
if d.waitCh != nil {
d.waitingCh <- struct{}{}
<-d.waitCh
d.waitCh = nil
d.waitingCh = nil
}
return conn, nil
}
func (d *fakeDriver) getDB(name string) *fakeDB {
d.mu.Lock()
defer d.mu.Unlock()
if d.dbs == nil {
d.dbs = make(map[string]*fakeDB)
}
db, ok := d.dbs[name]
if !ok {
db = &fakeDB{name: name}
d.dbs[name] = db
}
return db
}
func (db *fakeDB) wipe() {
db.mu.Lock()
defer db.mu.Unlock()
db.tables = nil
}
func (db *fakeDB) createTable(name string, columnNames, columnTypes []string) error {
db.mu.Lock()
defer db.mu.Unlock()
if db.tables == nil {
db.tables = make(map[string]*table)
}
if _, exist := db.tables[name]; exist {
return fmt.Errorf("fakedb: table %q already exists", name)
}
if len(columnNames) != len(columnTypes) {
return fmt.Errorf("fakedb: create table of %q len(names) != len(types): %d vs %d",
name, len(columnNames), len(columnTypes))
}
db.tables[name] = &table{colname: columnNames, coltype: columnTypes}
return nil
}
// must be called with db.mu lock held
func (db *fakeDB) table(table string) (*table, bool) {
if db.tables == nil {
return nil, false
}
t, ok := db.tables[table]
return t, ok
}
func (db *fakeDB) columnType(table, column string) (typ string, ok bool) {
db.mu.Lock()
defer db.mu.Unlock()
t, ok := db.table(table)
if !ok {
return
}
for n, cname := range t.colname {
if cname == column {
return t.coltype[n], true
}
}
return "", false
}
func (c *fakeConn) isBad() bool {
if c.stickyBad {
return true
} else if c.bad {
if c.db == nil {
return false
}
// alternate between bad conn and not bad conn
c.db.badConn = !c.db.badConn
return c.db.badConn
} else {
return false
}
}
func (c *fakeConn) isDirtyAndMark() bool {
if c.skipDirtySession {
return false
}
if c.currTx != nil {
c.dirtySession = true
return false
}
if c.dirtySession {
return true
}
c.dirtySession = true
return false
}
func (c *fakeConn) Begin() (driver.Tx, error) {
if c.isBad() {
return nil, fakeError{Wrapped: driver.ErrBadConn}
}
if c.currTx != nil {
return nil, errors.New("fakedb: already in a transaction")
}
c.touchMem()
c.currTx = &fakeTx{c: c}
return c.currTx, nil
}
var hookPostCloseConn struct {
sync.Mutex
fn func(*fakeConn, error)
}
func setHookpostCloseConn(fn func(*fakeConn, error)) {
hookPostCloseConn.Lock()
defer hookPostCloseConn.Unlock()
hookPostCloseConn.fn = fn
}
var testStrictClose *testing.T
// setStrictFakeConnClose sets the t to Errorf on when fakeConn.Close
// fails to close. If nil, the check is disabled.
func setStrictFakeConnClose(t *testing.T) {
testStrictClose = t
}
func (c *fakeConn) ResetSession(ctx context.Context) error {
c.dirtySession = false
c.currTx = nil
if c.isBad() {
return fakeError{Message: "Reset Session: bad conn", Wrapped: driver.ErrBadConn}
}
return nil
}
var _ driver.Validator = (*fakeConn)(nil)
func (c *fakeConn) IsValid() bool {
return !c.isBad()
}
func (c *fakeConn) Close() (err error) {
drv := fdriver.(*fakeDriver)
defer func() {
if err != nil && testStrictClose != nil {
testStrictClose.Errorf("failed to close a test fakeConn: %v", err)
}
hookPostCloseConn.Lock()
fn := hookPostCloseConn.fn
hookPostCloseConn.Unlock()
if fn != nil {
fn(c, err)
}
if err == nil {
drv.mu.Lock()
drv.closeCount++
drv.mu.Unlock()
}
}()
c.touchMem()
if c.currTx != nil {
return errors.New("fakedb: can't close fakeConn; in a Transaction")
}
if c.db == nil {
return errors.New("fakedb: can't close fakeConn; already closed")
}
if c.stmtsMade > c.stmtsClosed {
return errors.New("fakedb: can't close; dangling statement(s)")
}
c.db = nil
return nil
}
func checkSubsetTypes(allowAny bool, args []driver.NamedValue) error {
for _, arg := range args {
switch arg.Value.(type) {
case int64, float64, bool, nil, []byte, string, time.Time:
default:
if !allowAny {
return fmt.Errorf("fakedb: invalid argument ordinal %[1]d: %[2]v, type %[2]T", arg.Ordinal, arg.Value)
}
}
}
return nil
}
func (c *fakeConn) Exec(query string, args []driver.Value) (driver.Result, error) {
// Ensure that ExecContext is called if available.
panic("ExecContext was not called.")
}
func (c *fakeConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
// This is an optional interface, but it's implemented here
// just to check that all the args are of the proper types.
// ErrSkip is returned so the caller acts as if we didn't
// implement this at all.
err := checkSubsetTypes(c.db.allowAny, args)
if err != nil {
return nil, err
}
return nil, driver.ErrSkip
}
func (c *fakeConn) Query(query string, args []driver.Value) (driver.Rows, error) {
// Ensure that ExecContext is called if available.
panic("QueryContext was not called.")
}
func (c *fakeConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
// This is an optional interface, but it's implemented here
// just to check that all the args are of the proper types.
// ErrSkip is returned so the caller acts as if we didn't
// implement this at all.
err := checkSubsetTypes(c.db.allowAny, args)
if err != nil {
return nil, err
}
return nil, driver.ErrSkip
}
func errf(msg string, args ...any) error {
return errors.New("fakedb: " + fmt.Sprintf(msg, args...))
}
// parts are table|selectCol1,selectCol2|whereCol=?,whereCol2=?
// (note that where columns must always contain ? marks,
// just a limitation for fakedb)
func (c *fakeConn) prepareSelect(stmt *fakeStmt, parts []string) (*fakeStmt, error) {
if len(parts) != 3 {
stmt.Close()
return nil, errf("invalid SELECT syntax with %d parts; want 3", len(parts))
}
stmt.table = parts[0]
stmt.colName = strings.Split(parts[1], ",")
for n, colspec := range strings.Split(parts[2], ",") {
if colspec == "" {
continue
}
nameVal := strings.Split(colspec, "=")
if len(nameVal) != 2 {
stmt.Close()
return nil, errf("SELECT on table %q has invalid column spec of %q (index %d)", stmt.table, colspec, n)
}
column, value := nameVal[0], nameVal[1]
_, ok := c.db.columnType(stmt.table, column)
if !ok {
stmt.Close()
return nil, errf("SELECT on table %q references non-existent column %q", stmt.table, column)
}
if !strings.HasPrefix(value, "?") {
stmt.Close()
return nil, errf("SELECT on table %q has pre-bound value for where column %q; need a question mark",
stmt.table, column)
}
stmt.placeholders++
stmt.whereCol = append(stmt.whereCol, boundCol{Column: column, Placeholder: value, Ordinal: stmt.placeholders})
}
return stmt, nil
}
// parts are table|col=type,col2=type2
func (c *fakeConn) prepareCreate(stmt *fakeStmt, parts []string) (*fakeStmt, error) {
if len(parts) != 2 {
stmt.Close()
return nil, errf("invalid CREATE syntax with %d parts; want 2", len(parts))
}
stmt.table = parts[0]
for n, colspec := range strings.Split(parts[1], ",") {
nameType := strings.Split(colspec, "=")
if len(nameType) != 2 {
stmt.Close()
return nil, errf("CREATE table %q has invalid column spec of %q (index %d)", stmt.table, colspec, n)
}
stmt.colName = append(stmt.colName, nameType[0])
stmt.colType = append(stmt.colType, nameType[1])
}
return stmt, nil
}
// parts are table|col=?,col2=val
func (c *fakeConn) prepareInsert(ctx context.Context, stmt *fakeStmt, parts []string) (*fakeStmt, error) {
if len(parts) != 2 {
stmt.Close()
return nil, errf("invalid INSERT syntax with %d parts; want 2", len(parts))
}
stmt.table = parts[0]
for n, colspec := range strings.Split(parts[1], ",") {
nameVal := strings.Split(colspec, "=")
if len(nameVal) != 2 {
stmt.Close()
return nil, errf("INSERT table %q has invalid column spec of %q (index %d)", stmt.table, colspec, n)
}
column, value := nameVal[0], nameVal[1]
ctype, ok := c.db.columnType(stmt.table, column)
if !ok {
stmt.Close()
return nil, errf("INSERT table %q references non-existent column %q", stmt.table, column)
}
stmt.colName = append(stmt.colName, column)
if !strings.HasPrefix(value, "?") {
var subsetVal any
// Convert to driver subset type
switch ctype {
case "string":
subsetVal = []byte(value)
case "blob":
subsetVal = []byte(value)
case "int32":
i, err := strconv.Atoi(value)
if err != nil {
stmt.Close()
return nil, errf("invalid conversion to int32 from %q", value)
}
subsetVal = int64(i) // int64 is a subset type, but not int32
case "table": // For testing cursor reads.
c.skipDirtySession = true
vparts := strings.Split(value, "!")
substmt, err := c.PrepareContext(ctx, fmt.Sprintf("SELECT|%s|%s|", vparts[0], strings.Join(vparts[1:], ",")))
if err != nil {
return nil, err
}
cursor, err := (substmt.(driver.StmtQueryContext)).QueryContext(ctx, []driver.NamedValue{})
substmt.Close()
if err != nil {
return nil, err
}
subsetVal = cursor
default:
stmt.Close()
return nil, errf("unsupported conversion for pre-bound parameter %q to type %q", value, ctype)
}
stmt.colValue = append(stmt.colValue, subsetVal)
} else {
stmt.placeholders++
stmt.placeholderConverter = append(stmt.placeholderConverter, converterForType(ctype))
stmt.colValue = append(stmt.colValue, value)
}
}
return stmt, nil
}
// hook to simulate broken connections
var hookPrepareBadConn func() bool
func (c *fakeConn) Prepare(query string) (driver.Stmt, error) {
panic("use PrepareContext")
}
func (c *fakeConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
c.numPrepare++
if c.db == nil {
panic("nil c.db; conn = " + fmt.Sprintf("%#v", c))
}
if c.stickyBad || (hookPrepareBadConn != nil && hookPrepareBadConn()) {
return nil, fakeError{Message: "Prepare: Sticky Bad", Wrapped: driver.ErrBadConn}
}
c.touchMem()
var firstStmt, prev *fakeStmt
for _, query := range strings.Split(query, ";") {
parts := strings.Split(query, "|")
if len(parts) < 1 {
return nil, errf("empty query")
}
stmt := &fakeStmt{q: query, c: c, memToucher: c}
if firstStmt == nil {
firstStmt = stmt
}
if len(parts) >= 3 {
switch parts[0] {
case "PANIC":
stmt.panic = parts[1]
parts = parts[2:]
case "WAIT":
wait, err := time.ParseDuration(parts[1])
if err != nil {
return nil, errf("expected section after WAIT to be a duration, got %q %v", parts[1], err)
}
parts = parts[2:]
stmt.wait = wait
}
}
cmd := parts[0]
stmt.cmd = cmd
parts = parts[1:]
if c.waiter != nil {
c.waiter(ctx)
if err := ctx.Err(); err != nil {
return nil, err
}
}
if stmt.wait > 0 {
wait := time.NewTimer(stmt.wait)
select {
case <-wait.C:
case <-ctx.Done():
wait.Stop()
return nil, ctx.Err()
}
}
c.incrStat(&c.stmtsMade)
var err error
switch cmd {
case "WIPE":
// Nothing
case "USE_RAWBYTES":
c.db.useRawBytes.Store(true)
case "SELECT":
stmt, err = c.prepareSelect(stmt, parts)
case "CREATE":
stmt, err = c.prepareCreate(stmt, parts)
case "INSERT":
stmt, err = c.prepareInsert(ctx, stmt, parts)
case "NOSERT":
// Do all the prep-work like for an INSERT but don't actually insert the row.
// Used for some of the concurrent tests.
stmt, err = c.prepareInsert(ctx, stmt, parts)
default:
stmt.Close()
return nil, errf("unsupported command type %q", cmd)
}
if err != nil {
return nil, err
}
if prev != nil {
prev.next = stmt
}
prev = stmt
}
return firstStmt, nil
}
func (s *fakeStmt) ColumnConverter(idx int) driver.ValueConverter {
if s.panic == "ColumnConverter" {
panic(s.panic)
}
if len(s.placeholderConverter) == 0 {
return driver.DefaultParameterConverter
}
return s.placeholderConverter[idx]
}
func (s *fakeStmt) Close() error {
if s.panic == "Close" {
panic(s.panic)
}
if s.c == nil {
panic("nil conn in fakeStmt.Close")
}
if s.c.db == nil {
panic("in fakeStmt.Close, conn's db is nil (already closed)")
}
s.touchMem()
if !s.closed {
s.c.incrStat(&s.c.stmtsClosed)
s.closed = true
}
if s.next != nil {
s.next.Close()
}
return nil
}
var errClosed = errors.New("fakedb: statement has been closed")
// hook to simulate broken connections
var hookExecBadConn func() bool
func (s *fakeStmt) Exec(args []driver.Value) (driver.Result, error) {
panic("Using ExecContext")
}
var errFakeConnSessionDirty = errors.New("fakedb: session is dirty")
func (s *fakeStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) {
if s.panic == "Exec" {
panic(s.panic)
}
if s.closed {
return nil, errClosed
}
if s.c.stickyBad || (hookExecBadConn != nil && hookExecBadConn()) {
return nil, fakeError{Message: "Exec: Sticky Bad", Wrapped: driver.ErrBadConn}
}
if s.c.isDirtyAndMark() {
return nil, errFakeConnSessionDirty
}
err := checkSubsetTypes(s.c.db.allowAny, args)
if err != nil {
return nil, err
}
s.touchMem()
if s.wait > 0 {
time.Sleep(s.wait)
}
select {
default:
case <-ctx.Done():
return nil, ctx.Err()
}
db := s.c.db
switch s.cmd {
case "WIPE":
db.wipe()
return driver.ResultNoRows, nil
case "USE_RAWBYTES":
s.c.db.useRawBytes.Store(true)
return driver.ResultNoRows, nil
case "CREATE":
if err := db.createTable(s.table, s.colName, s.colType); err != nil {
return nil, err
}
return driver.ResultNoRows, nil
case "INSERT":
return s.execInsert(args, true)
case "NOSERT":
// Do all the prep-work like for an INSERT but don't actually insert the row.
// Used for some of the concurrent tests.
return s.execInsert(args, false)
}
return nil, fmt.Errorf("fakedb: unimplemented statement Exec command type of %q", s.cmd)
}
// When doInsert is true, add the row to the table.
// When doInsert is false do prep-work and error checking, but don't
// actually add the row to the table.
func (s *fakeStmt) execInsert(args []driver.NamedValue, doInsert bool) (driver.Result, error) {
db := s.c.db
if len(args) != s.placeholders {
panic("error in pkg db; should only get here if size is correct")
}
db.mu.Lock()
t, ok := db.table(s.table)
db.mu.Unlock()
if !ok {
return nil, fmt.Errorf("fakedb: table %q doesn't exist", s.table)
}
t.mu.Lock()
defer t.mu.Unlock()
var cols []any
if doInsert {
cols = make([]any, len(t.colname))
}
argPos := 0
for n, colname := range s.colName {
colidx := t.columnIndex(colname)
if colidx == -1 {
return nil, fmt.Errorf("fakedb: column %q doesn't exist or dropped since prepared statement was created", colname)
}
var val any
if strvalue, ok := s.colValue[n].(string); ok && strings.HasPrefix(strvalue, "?") {
if strvalue == "?" {
val = args[argPos].Value
} else {
// Assign value from argument placeholder name.
for _, a := range args {
if a.Name == strvalue[1:] {
val = a.Value
break
}
}
}
argPos++
} else {
val = s.colValue[n]
}
if doInsert {
cols[colidx] = val
}
}
if doInsert {
t.rows = append(t.rows, &row{cols: cols})
}
return driver.RowsAffected(1), nil
}
// hook to simulate broken connections
var hookQueryBadConn func() bool
func (s *fakeStmt) Query(args []driver.Value) (driver.Rows, error) {
panic("Use QueryContext")
}
func (s *fakeStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) {
if s.panic == "Query" {
panic(s.panic)
}
if s.closed {
return nil, errClosed
}
if s.c.stickyBad || (hookQueryBadConn != nil && hookQueryBadConn()) {
return nil, fakeError{Message: "Query: Sticky Bad", Wrapped: driver.ErrBadConn}
}
if s.c.isDirtyAndMark() {
return nil, errFakeConnSessionDirty
}
err := checkSubsetTypes(s.c.db.allowAny, args)
if err != nil {
return nil, err
}
s.touchMem()
db := s.c.db
if len(args) != s.placeholders {
panic("error in pkg db; should only get here if size is correct")
}
setMRows := make([][]*row, 0, 1)
setColumns := make([][]string, 0, 1)
setColType := make([][]string, 0, 1)
for {
db.mu.Lock()
t, ok := db.table(s.table)
db.mu.Unlock()
if !ok {
return nil, fmt.Errorf("fakedb: table %q doesn't exist", s.table)
}
if s.table == "magicquery" {
if len(s.whereCol) == 2 && s.whereCol[0].Column == "op" && s.whereCol[1].Column == "millis" {
if args[0].Value == "sleep" {
time.Sleep(time.Duration(args[1].Value.(int64)) * time.Millisecond)
}
}
}
if s.table == "tx_status" && s.colName[0] == "tx_status" {
txStatus := "autocommit"
if s.c.currTx != nil {
txStatus = "transaction"
}
cursor := &rowsCursor{
db: s.c.db,
parentMem: s.c,
posRow: -1,
rows: [][]*row{
{
{
cols: []any{
txStatus,
},
},
},
},
cols: [][]string{
{
"tx_status",
},
},
colType: [][]string{
{
"string",
},
},
errPos: -1,
}
return cursor, nil
}
t.mu.Lock()
colIdx := make(map[string]int) // select column name -> column index in table
for _, name := range s.colName {
idx := t.columnIndex(name)
if idx == -1 {