-
Notifications
You must be signed in to change notification settings - Fork 21
/
libsql_test.go
1361 lines (1249 loc) · 33.4 KB
/
libsql_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
package libsql
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"gotest.tools/assert"
"io"
"math/rand"
"net/http"
"os"
"runtime/debug"
"strings"
"testing"
"time"
"golang.org/x/sync/errgroup"
)
type T struct {
*testing.T
}
func (t T) FatalWithMsg(msg string) {
t.Log(string(debug.Stack()))
t.Fatal(msg)
}
func (t T) FatalOnError(err error) {
if err != nil {
t.Log(string(debug.Stack()))
t.Fatal(err)
}
}
func getRemoteDb(t T) *Database {
primaryUrl := os.Getenv("LIBSQL_PRIMARY_URL")
if primaryUrl == "" {
t.Skip("LIBSQL_PRIMARY_URL is not set")
return nil
}
authToken := os.Getenv("LIBSQL_AUTH_TOKEN")
db, err := sql.Open("libsql", primaryUrl+"?authToken="+authToken)
t.FatalOnError(err)
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
t.Cleanup(func() {
db.Close()
cancel()
})
return &Database{db, nil, t, ctx}
}
func getEmbeddedDb(t T) *Database {
primaryUrl := os.Getenv("LIBSQL_PRIMARY_URL")
if primaryUrl == "" {
t.Skip("LIBSQL_PRIMARY_URL is not set")
return nil
}
authToken := os.Getenv("LIBSQL_AUTH_TOKEN")
dir, err := os.MkdirTemp("", "libsql-*")
if err != nil {
t.Fatal(err)
}
dbPath := dir + "/test.db"
options := []Option{WithReadYourWrites(false)}
if authToken != "" {
options = append(options, WithAuthToken(authToken))
}
connector, err := NewEmbeddedReplicaConnector(dbPath, primaryUrl, options...)
t.FatalOnError(err)
db := sql.OpenDB(connector)
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
t.Cleanup(func() {
db.Close()
connector.Close()
cancel()
defer os.RemoveAll(dir)
})
return &Database{db, connector, t, ctx}
}
type Database struct {
*sql.DB
connector *Connector
t T
ctx context.Context
}
func (db Database) exec(sql string, args ...any) sql.Result {
res, err := db.ExecContext(db.ctx, sql, args...)
db.t.FatalOnError(err)
return res
}
func (db Database) query(sql string, args ...any) *sql.Rows {
rows, err := db.QueryContext(db.ctx, sql, args...)
db.t.FatalOnError(err)
return rows
}
func (db Database) sync() {
if db.connector != nil {
db.connector.Sync()
}
}
type Table struct {
name string
db Database
}
func (db Database) createTable() Table {
name := "test_" + fmt.Sprint(rand.Int()) + "_" + time.Now().Format("20060102150405")
db.exec("CREATE TABLE " + name + " (a int, b int)")
db.t.Cleanup(func() {
db.exec("DROP TABLE " + name)
})
return Table{name, db}
}
func (db Database) assertTable(name string) {
rows, err := db.QueryContext(db.ctx, "select 1 from "+name)
db.t.FatalOnError(err)
defer rows.Close()
}
func (t Table) insertRows(start, count int) {
t.insertRowsInternal(start, count, func(i int) sql.Result {
return t.db.exec("INSERT INTO " + t.name + " (a, b) VALUES (" + fmt.Sprint(i) + ", " + fmt.Sprint(i) + ")")
})
}
func (t Table) insertRowsWithArgs(start, count int) {
t.insertRowsInternal(start, count, func(i int) sql.Result {
return t.db.exec("INSERT INTO "+t.name+" (a, b) VALUES (?, ?)", i, i)
})
}
func (t Table) insertRowsInternal(start, count int, execFn func(i int) sql.Result) {
for i := 0; i < count; i++ {
execFn(i + start)
//Uncomment once RowsAffected is implemented in libsql for remote only dbs
//res := execFn(i + start)
//affected, err := res.RowsAffected()
//t.db.t.FatalOnError(err)
//if affected != 1 {
// t.db.t.FatalWithMsg("expected 1 row affected")
//}
}
}
func (t Table) assertRowsCount(count int) {
t.assertCount(count, func() *sql.Rows {
return t.db.query("SELECT COUNT(*) FROM " + t.name)
})
}
func (t Table) assertRowDoesNotExist(id int) {
t.assertCount(0, func() *sql.Rows {
return t.db.query("SELECT COUNT(*) FROM "+t.name+" WHERE a = ?", id)
})
}
func (t Table) assertRowExists(id int) {
t.assertCount(1, func() *sql.Rows {
return t.db.query("SELECT COUNT(*) FROM "+t.name+" WHERE a = ?", id)
})
}
func (t Table) assertCount(expectedCount int, queryFn func() *sql.Rows) {
rows := queryFn()
defer rows.Close()
if !rows.Next() {
t.db.t.FatalWithMsg(fmt.Sprintf("expected at least one row: %v", rows.Err()))
}
var rowCount int
t.db.t.FatalOnError(rows.Scan(&rowCount))
if rowCount != expectedCount {
t.db.t.FatalWithMsg(fmt.Sprintf("expected %d rows, got %d", expectedCount, rowCount))
}
}
func (t Table) beginTx() Tx {
tx, err := t.db.BeginTx(t.db.ctx, nil)
t.db.t.FatalOnError(err)
return Tx{tx, t, nil}
}
func (t Table) beginTxWithContext(ctx context.Context) Tx {
tx, err := t.db.BeginTx(ctx, nil)
t.db.t.FatalOnError(err)
return Tx{tx, t, &ctx}
}
func (t Table) prepareInsertStmt() PreparedStmt {
stmt, err := t.db.Prepare("INSERT INTO " + t.name + " (a, b) VALUES (?, ?)")
t.db.t.FatalOnError(err)
return PreparedStmt{stmt, t}
}
type PreparedStmt struct {
*sql.Stmt
t Table
}
func (s PreparedStmt) exec(args ...any) sql.Result {
res, err := s.ExecContext(s.t.db.ctx, args...)
s.t.db.t.FatalOnError(err)
return res
}
type Tx struct {
*sql.Tx
t Table
ctx *context.Context
}
func (t Tx) context() context.Context {
if t.ctx != nil {
return *t.ctx
}
return t.t.db.ctx
}
func (t Tx) exec(sql string, args ...any) sql.Result {
res, err := t.ExecContext(t.context(), sql, args...)
t.t.db.t.FatalOnError(err)
return res
}
func (t Tx) query(sql string, args ...any) *sql.Rows {
rows, err := t.QueryContext(t.context(), sql, args...)
t.t.db.t.FatalOnError(err)
return rows
}
func (t Tx) insertRows(start, count int) {
t.t.insertRowsInternal(start, count, func(i int) sql.Result {
return t.exec("INSERT INTO " + t.t.name + " (a, b) VALUES (" + fmt.Sprint(i) + ", '" + fmt.Sprint(i) + "')")
})
}
func (t Tx) insertRowsWithArgs(start, count int) {
t.t.insertRowsInternal(start, count, func(i int) sql.Result {
return t.exec("INSERT INTO "+t.t.name+" (a, b) VALUES (?, ?)", i, fmt.Sprint(i))
})
}
func (t Tx) assertRowsCount(count int) {
t.t.assertCount(count, func() *sql.Rows {
return t.query("SELECT COUNT(*) FROM " + t.t.name)
})
}
func (t Tx) assertRowDoesNotExist(id int) {
t.t.assertCount(0, func() *sql.Rows {
return t.query("SELECT COUNT(*) FROM "+t.t.name+" WHERE a = ?", id)
})
}
func (t Tx) assertRowExists(id int) {
t.t.assertCount(1, func() *sql.Rows {
return t.query("SELECT COUNT(*) FROM "+t.t.name+" WHERE a = ?", id)
})
}
func (t Tx) prepareInsertStmt() PreparedStmt {
stmt, err := t.Prepare("INSERT INTO " + t.t.name + " (a, b) VALUES (?, ?)")
t.t.db.t.FatalOnError(err)
return PreparedStmt{stmt, t.t}
}
func executeSql(t *testing.T, primaryUrl, authToken, sql string) {
type statement struct {
Query string `json:"q"`
}
type postBody struct {
Statements []statement `json:"statements"`
}
type resultSet struct {
Columns []string `json:"columns"`
}
type httpErrObject struct {
Message string `json:"message"`
}
type httpResults struct {
Results *resultSet `json:"results"`
Error *httpErrObject `json:"error"`
}
type httpResultsAlternative struct {
Results *resultSet `json:"results"`
Error string `json:"error"`
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
rawReq := postBody{}
rawReq.Statements = append(rawReq.Statements, statement{Query: sql})
body, err := json.Marshal(rawReq)
if err != nil {
t.Fatal(err)
}
req, err := http.NewRequestWithContext(ctx, "POST", primaryUrl+"", bytes.NewReader(body))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
if authToken != "" {
req.Header.Set("Authorization", "Bearer "+authToken)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
body, err = io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK {
t.Fatal("unexpected status code: ", resp.StatusCode)
}
var results []httpResults
err = json.Unmarshal(body, &results)
if err != nil {
var alternativeResults []httpResultsAlternative
errArray := json.Unmarshal(body, &alternativeResults)
if errArray != nil {
t.Fatal("failed to unmarshal response: ", err, errArray)
}
if alternativeResults[0].Error != "" {
t.Fatal(errors.New(alternativeResults[0].Error))
}
} else {
if results[0].Error != nil {
t.Fatal(errors.New(results[0].Error.Message))
}
if results[0].Results == nil {
t.Fatal(errors.New("no results"))
}
}
}
func insertRow(t *testing.T, dbUrl, authToken, tableName string, id int) {
executeSql(t, dbUrl, authToken, fmt.Sprintf("INSERT INTO %s (id, name, gpa, cv) VALUES (%d, '%d', %d.5, randomblob(10));", tableName, id, id, id))
}
func insertRows(t *testing.T, dbUrl, authToken, tableName string, start, count int) {
for i := 0; i < count; i++ {
insertRow(t, dbUrl, authToken, tableName, start+i)
}
}
func createTable(t *testing.T, dbPath, authToken string) string {
tableName := fmt.Sprintf("test_%d", time.Now().UnixNano())
executeSql(t, dbPath, authToken, fmt.Sprintf("CREATE TABLE %s (id INTEGER, name TEXT, gpa REAL, cv BLOB);", tableName))
return tableName
}
func removeTable(t *testing.T, dbPath, authToken, tableName string) {
executeSql(t, dbPath, authToken, fmt.Sprintf("DROP TABLE %s;", tableName))
}
func testSync(t *testing.T, connect func(dbPath, primaryUrl, authToken string) *Connector, sync func(connector *Connector)) {
primaryUrl := os.Getenv("LIBSQL_PRIMARY_URL")
if primaryUrl == "" {
t.Skip("LIBSQL_PRIMARY_URL is not set")
return
}
authToken := os.Getenv("LIBSQL_AUTH_TOKEN")
tableName := createTable(t, primaryUrl, authToken)
defer removeTable(t, primaryUrl, authToken, tableName)
initialRowsCount := 5
insertRows(t, primaryUrl, authToken, tableName, 0, initialRowsCount)
dir, err := os.MkdirTemp("", "libsql-*")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
connector := connect(dir+"/test.db", primaryUrl, authToken)
db := sql.OpenDB(connector)
defer db.Close()
iterCount := 2
for iter := 0; iter < iterCount; iter++ {
func() {
rows, err := db.QueryContext(context.Background(), "SELECT NULL, id, name, gpa, cv FROM "+tableName)
if err != nil {
t.Fatal(err)
}
columns, err := rows.Columns()
if err != nil {
t.Fatal(err)
}
assert.DeepEqual(t, columns, []string{"NULL", "id", "name", "gpa", "cv"})
types, err := rows.ColumnTypes()
if err != nil {
t.Fatal(err)
}
if len(types) != 5 {
t.Fatal("types should be 5")
}
defer rows.Close()
idx := 0
for rows.Next() {
if idx > initialRowsCount+iter {
t.Fatal("idx should be <= ", initialRowsCount+iter)
}
var null any
var id int
var name string
var gpa float64
var cv []byte
if err := rows.Scan(&null, &id, &name, &gpa, &cv); err != nil {
t.Fatal(err)
}
if null != nil {
t.Fatal("null should be nil")
}
if id != int(idx) {
t.Fatal("id should be ", idx, " got ", id)
}
if name != fmt.Sprint(idx) {
t.Fatal("name should be", idx)
}
if gpa != float64(idx)+0.5 {
t.Fatal("gpa should be", float64(idx)+0.5)
}
if len(cv) != 10 {
t.Fatal("cv should be 10 bytes")
}
idx++
}
if idx != initialRowsCount+iter {
t.Fatal("idx should be ", initialRowsCount+iter, " got ", idx)
}
}()
if iter+1 != iterCount {
insertRow(t, primaryUrl, authToken, tableName, initialRowsCount+iter)
sync(connector)
}
}
}
func TestAutoSync(t *testing.T) {
syncInterval := 1 * time.Second
testSync(t, func(dbPath, primaryUrl, authToken string) *Connector {
options := []Option{WithReadYourWrites(false), WithSyncInterval(syncInterval)}
if authToken != "" {
options = append(options, WithAuthToken(authToken))
}
connector, err := NewEmbeddedReplicaConnector(dbPath, primaryUrl, options...)
if err != nil {
t.Fatal(err)
}
return connector
}, func(_ *Connector) {
time.Sleep(2 * syncInterval)
})
}
func TestSync(t *testing.T) {
testSync(t, func(dbPath, primaryUrl, authToken string) *Connector {
options := []Option{WithReadYourWrites(false)}
if authToken != "" {
options = append(options, WithAuthToken(authToken))
}
connector, err := NewEmbeddedReplicaConnector(dbPath, primaryUrl, options...)
if err != nil {
t.Fatal(err)
}
return connector
}, func(c *Connector) {
if _, err := c.Sync(); err != nil {
t.Fatal(err)
}
})
}
func TestEncryption(tt *testing.T) {
t := T{tt}
primaryUrl := os.Getenv("LIBSQL_PRIMARY_URL")
if primaryUrl == "" {
t.Skip("LIBSQL_PRIMARY_URL is not set")
return
}
authToken := os.Getenv("LIBSQL_AUTH_TOKEN")
dir, err := os.MkdirTemp("", "libsql-*")
if err != nil {
t.Fatal(err)
}
dbPath := dir + "/test.db"
t.Cleanup(func() {
defer os.RemoveAll(dir)
})
encryptionKey := "SuperSecretKey"
table := "test_" + fmt.Sprint(rand.Int()) + "_" + time.Now().Format("20060102150405")
options := []Option{WithReadYourWrites(false)}
if authToken != "" {
options = append(options, WithAuthToken(authToken))
}
connector, err := NewEmbeddedReplicaConnector(dbPath, primaryUrl, append(options, WithEncryption(encryptionKey))...)
t.FatalOnError(err)
db := sql.OpenDB(connector)
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
_, err = db.ExecContext(ctx, "CREATE TABLE "+table+" (id INTEGER PRIMARY KEY, name TEXT)")
if err != nil {
cancel()
db.Close()
connector.Close()
t.FatalOnError(err)
}
_, err = db.ExecContext(ctx, "INSERT INTO "+table+" (id, name) VALUES (1, 'hello')")
if err != nil {
cancel()
db.Close()
connector.Close()
t.FatalOnError(err)
}
err = db.Close()
t.FatalOnError(err)
err = connector.Close()
t.FatalOnError(err)
connector, err = NewEmbeddedReplicaConnector(dbPath, primaryUrl, append(options, WithEncryption(encryptionKey))...)
t.FatalOnError(err)
db = sql.OpenDB(connector)
rows, err := db.QueryContext(ctx, "SELECT * FROM "+table)
if err != nil {
cancel()
db.Close()
connector.Close()
t.FatalOnError(err)
}
defer rows.Close()
if !rows.Next() {
cancel()
db.Close()
connector.Close()
t.Fatal("expected one row")
}
var id int
var name string
err = rows.Scan(&id, &name)
if err != nil {
cancel()
db.Close()
connector.Close()
t.FatalOnError(err)
}
if id != 1 {
cancel()
db.Close()
connector.Close()
t.Fatal("id should be 1")
}
if name != "hello" {
cancel()
db.Close()
connector.Close()
t.Fatal("name should be hello")
}
err = rows.Close()
t.FatalOnError(err)
err = db.Close()
t.FatalOnError(err)
err = connector.Close()
t.FatalOnError(err)
connector, err = NewEmbeddedReplicaConnector(dbPath, primaryUrl, append(options, WithEncryption("WrongKey"))...)
if err == nil {
t.Fatal("using wrong encryption key should have failed")
}
if !strings.Contains(err.Error(), "SQLite error: file is not a database") {
t.Fatal("using wrong encryption key should have failed with a different error")
}
}
func TestExecAndQuery(t *testing.T) {
db := getRemoteDb(T{t})
testExecAndQuery(db)
}
func TestExecAndQueryEmbedded(t *testing.T) {
db := getEmbeddedDb(T{t})
testExecAndQuery(db)
}
func testExecAndQuery(db *Database) {
if db == nil {
return
}
table := db.createTable()
table.insertRows(0, 10)
table.insertRowsWithArgs(10, 10)
db.sync()
table.assertRowsCount(20)
table.assertRowDoesNotExist(20)
table.assertRowExists(0)
table.assertRowExists(19)
}
func TestReadYourWrites(tt *testing.T) {
t := T{tt}
primaryUrl := os.Getenv("LIBSQL_PRIMARY_URL")
if primaryUrl == "" {
t.Skip("LIBSQL_PRIMARY_URL is not set")
return
}
authToken := os.Getenv("LIBSQL_AUTH_TOKEN")
dir, err := os.MkdirTemp("", "libsql-*")
if err != nil {
t.Fatal(err)
}
dbPath := dir + "/test.db"
options := []Option{}
if authToken != "" {
options = append(options, WithAuthToken(authToken))
}
connector, err := NewEmbeddedReplicaConnector(dbPath, primaryUrl, options...)
t.FatalOnError(err)
database := sql.OpenDB(connector)
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
t.Cleanup(func() {
database.Close()
connector.Close()
cancel()
defer os.RemoveAll(dir)
})
db := &Database{database, connector, t, ctx}
table := db.createTable()
table.insertRows(0, 10)
table.insertRowsWithArgs(10, 10)
table.assertRowsCount(20)
table.assertRowDoesNotExist(20)
table.assertRowExists(0)
table.assertRowExists(19)
}
func TestPreparedStatements(t *testing.T) {
db := getRemoteDb(T{t})
testPreparedStatements(db)
}
func TestPreparedStatementsEmbedded(t *testing.T) {
db := getEmbeddedDb(T{t})
testPreparedStatements(db)
}
func testPreparedStatements(db *Database) {
if db == nil {
return
}
table := db.createTable()
stmt := table.prepareInsertStmt()
stmt.exec(1, "1")
db.t.FatalOnError(stmt.Close())
db.sync()
table.assertRowsCount(1)
table.assertRowExists(1)
}
func TestTransaction(t *testing.T) {
db := getRemoteDb(T{t})
testTransaction(db)
}
func TestTransactionEmbedded(t *testing.T) {
db := getEmbeddedDb(T{t})
testTransaction(db)
}
func testTransaction(db *Database) {
if db == nil {
return
}
table := db.createTable()
tx := table.beginTx()
tx.insertRows(0, 10)
tx.insertRowsWithArgs(10, 10)
tx.assertRowsCount(20)
tx.assertRowDoesNotExist(20)
tx.assertRowExists(0)
tx.assertRowExists(19)
db.t.FatalOnError(tx.Commit())
db.sync()
table.assertRowsCount(20)
table.assertRowDoesNotExist(20)
table.assertRowExists(0)
table.assertRowExists(19)
}
func TestMultiLineStatement(t *testing.T) {
t.Skip("Make it work")
db := getRemoteDb(T{t})
if db == nil {
return
}
db.exec("CREATE TABLE IF NOT EXISTS my_table (my_data TEXT); INSERT INTO my_table (my_data) VALUES ('hello');")
t.Cleanup(func() {
db.exec("DROP TABLE my_table")
})
table := Table{"my_table", *db}
db.assertTable("my_table")
table.assertRowsCount(1)
}
func TestPreparedStatementInTransaction(t *testing.T) {
db := getRemoteDb(T{t})
testPreparedStatementInTransaction(db)
}
func TestPreparedStatementInTransactionEmbedded(t *testing.T) {
db := getEmbeddedDb(T{t})
testPreparedStatementInTransaction(db)
}
func testPreparedStatementInTransaction(db *Database) {
if db == nil {
return
}
table := db.createTable()
tx := table.beginTx()
stmt := tx.prepareInsertStmt()
stmt.exec(1, "1")
db.t.FatalOnError(stmt.Close())
tx.assertRowsCount(1)
tx.assertRowExists(1)
db.t.FatalOnError(tx.Commit())
db.sync()
table.assertRowsCount(1)
table.assertRowExists(1)
}
func TestPreparedStatementInTransactionRollback(t *testing.T) {
db := getRemoteDb(T{t})
testPreparedStatementInTransactionRollback(db)
}
func TestPreparedStatementInTransactionRollbackEmbedded(t *testing.T) {
db := getEmbeddedDb(T{t})
testPreparedStatementInTransactionRollback(db)
}
func testPreparedStatementInTransactionRollback(db *Database) {
if db == nil {
return
}
table := db.createTable()
tx := table.beginTx()
stmt := tx.prepareInsertStmt()
stmt.exec(1, "1")
db.t.FatalOnError(stmt.Close())
tx.assertRowsCount(1)
tx.assertRowExists(1)
db.t.FatalOnError(tx.Rollback())
db.sync()
table.assertRowsCount(0)
table.assertRowDoesNotExist(1)
}
func TestCancelContext(t *testing.T) {
db := getRemoteDb(T{t})
testCancelContext(db)
}
func TestCancelContextEmbedded(t *testing.T) {
db := getEmbeddedDb(T{t})
testCancelContext(db)
}
func testCancelContext(db *Database) {
if db == nil {
return
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := db.ExecContext(ctx, "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, name TEXT)")
if err == nil {
db.t.FatalWithMsg("should have failed")
}
if !errors.Is(err, context.Canceled) {
db.t.FatalWithMsg("should have failed with context.Canceled")
}
}
func TestCancelContextWithTransaction(t *testing.T) {
db := getRemoteDb(T{t})
testCancelContextWithTransaction(db)
}
func TestCancelContextWithTransactionEmbedded(t *testing.T) {
db := getEmbeddedDb(T{t})
testCancelContextWithTransaction(db)
}
func testCancelContextWithTransaction(db *Database) {
if db == nil {
return
}
table := db.createTable()
ctx, cancel := context.WithCancel(context.Background())
tx := table.beginTxWithContext(ctx)
tx.insertRows(0, 10)
tx.insertRowsWithArgs(10, 10)
tx.assertRowsCount(20)
tx.assertRowDoesNotExist(20)
tx.assertRowExists(0)
tx.assertRowExists(19)
// let's cancel the context before the commit
cancel()
err := tx.Commit()
if err == nil {
db.t.FatalWithMsg("should have failed")
}
if !errors.Is(err, context.Canceled) {
db.t.FatalWithMsg("should have failed with context.Canceled")
}
// rolling back the transaction should not result in any error
db.t.FatalOnError(tx.Rollback())
}
func TestTransactionRollback(t *testing.T) {
db := getRemoteDb(T{t})
testTransactionRollback(db)
}
func TestTransactionRollbackEmbedded(t *testing.T) {
db := getEmbeddedDb(T{t})
testTransactionRollback(db)
}
func testTransactionRollback(db *Database) {
if db == nil {
return
}
table := db.createTable()
tx := table.beginTx()
tx.insertRows(0, 10)
tx.insertRowsWithArgs(10, 10)
tx.assertRowsCount(20)
tx.assertRowDoesNotExist(20)
tx.assertRowExists(0)
tx.assertRowExists(19)
db.t.FatalOnError(tx.Rollback())
db.sync()
table.assertRowsCount(0)
}
func TestArguments(t *testing.T) {
db := getRemoteDb(T{t})
testArguments(db)
}
func TestArgumentsEmbedded(t *testing.T) {
db := getEmbeddedDb(T{t})
testArguments(db)
}
func testArguments(db *Database) {
if db == nil {
return
}
t := db.t
tableName := fmt.Sprintf("test_%d", time.Now().UnixNano())
_, err := db.Exec(fmt.Sprintf("CREATE TABLE %s (id INTEGER, name TEXT, gpa REAL, cv BLOB);", tableName))
if err != nil {
t.Fatal(err)
}
_, err = db.Exec(fmt.Sprintf("INSERT INTO %s (id, name, gpa, cv) VALUES (?, ?, ?, randomblob(10));", tableName), 0, fmt.Sprint(0), 0.5)
if err != nil {
t.Fatal(err)
}
db.sync()
rows, err := db.QueryContext(context.Background(), "SELECT NULL, id, name, gpa, cv FROM "+tableName)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
idx := 0
for rows.Next() {
if idx > 0 {
t.Fatal("idx should be <= ", 0)
}
var null any
var id int
var name string
var gpa float64
var cv []byte
if err := rows.Scan(&null, &id, &name, &gpa, &cv); err != nil {
t.Fatal(err)
}
if null != nil {
t.Fatal("null should be nil")
}
if id != int(idx) {
t.Fatal("id should be ", idx, " got ", id)
}
if name != fmt.Sprint(idx) {
t.Fatal("name should be", idx)
}
if gpa != float64(idx)+0.5 {
t.Fatal("gpa should be", float64(idx)+0.5)
}
if len(cv) != 10 {
t.Fatal("cv should be 10 bytes")
}
idx++
}
if idx != 1 {
t.Fatal("idx should be 1 got ", idx)
}
}
func TestPing(t *testing.T) {
db := getRemoteDb(T{t})
testPing(db)
}
func TestPingEmbedded(t *testing.T) {
db := getEmbeddedDb(T{t})
testPing(db)
}
func testPing(db *Database) {
if db == nil {
return
}
// This ping should succeed because the database is up and running
db.t.FatalOnError(db.Ping())
db.t.Cleanup(func() {
db.Close()
// This ping should return an error because the database is already closed
err := db.Ping()
if err == nil {
db.t.Fatal("db.Ping succeeded when it should have failed")
}
})
}
func TestDataTypes(t *testing.T) {
db := getRemoteDb(T{t})
testDataTypes(db)
}
func TestDataTypesEmbedded(t *testing.T) {
db := getEmbeddedDb(T{t})
testDataTypes(db)
}
func testDataTypes(db *Database) {
if db == nil {
return
}
var (
text string
nullText sql.NullString
integer sql.NullInt64
nullInteger sql.NullInt64
boolean bool
float8 float64
nullFloat sql.NullFloat64
bytea []byte
Time time.Time
)
t := db.t
db.t.FatalOnError(db.QueryRowContext(db.ctx, "SELECT 'foobar' as text, NULL as text, NULL as integer, 42 as integer, 1 as boolean, X'000102' as bytea, 3.14 as float8, NULL as float8, '0001-01-01 01:00:00+00:00' as time;").Scan(&text, &nullText, &nullInteger, &integer, &boolean, &bytea, &float8, &nullFloat, &Time))
switch {
case text != "foobar":
t.Error("value mismatch - text")
case nullText.Valid:
t.Error("null text is valid")
case nullInteger.Valid:
t.Error("null integer is valid")
case !integer.Valid:
t.Error("integer is not valid")
case integer.Int64 != 42:
t.Error("value mismatch - integer")
case !boolean:
t.Error("value mismatch - boolean")
case float8 != 3.14:
t.Error("value mismatch - float8")
case !bytes.Equal(bytea, []byte{0, 1, 2}):
t.Error("value mismatch - bytea")