-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlite.go
2499 lines (2180 loc) · 66.3 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
// Copyright 2017 The Sqlite Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:generate go run generator.go -full-path-comments
package sqlite // import "modernc.org/sqlite"
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"io"
"math"
"math/bits"
"net/url"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
"modernc.org/libc"
"modernc.org/libc/sys/types"
sqlite3 "modernc.org/sqlite/lib"
)
var (
_ driver.Conn = (*conn)(nil)
_ driver.Driver = (*Driver)(nil)
//lint:ignore SA1019 TODO implement ExecerContext
_ driver.Execer = (*conn)(nil)
//lint:ignore SA1019 TODO implement QueryerContext
_ driver.Queryer = (*conn)(nil)
_ driver.Result = (*result)(nil)
_ driver.Rows = (*rows)(nil)
_ driver.RowsColumnTypeDatabaseTypeName = (*rows)(nil)
_ driver.RowsColumnTypeLength = (*rows)(nil)
_ driver.RowsColumnTypeNullable = (*rows)(nil)
_ driver.RowsColumnTypePrecisionScale = (*rows)(nil)
_ driver.RowsColumnTypeScanType = (*rows)(nil)
_ driver.Stmt = (*stmt)(nil)
_ driver.Tx = (*tx)(nil)
_ error = (*Error)(nil)
)
const (
driverName = "sqlite"
ptrSize = unsafe.Sizeof(uintptr(0))
sqliteLockedSharedcache = sqlite3.SQLITE_LOCKED | (1 << 8)
)
// Error represents sqlite library error code.
type Error struct {
msg string
code int
}
// Error implements error.
func (e *Error) Error() string { return e.msg }
// Code returns the sqlite result code for this error.
func (e *Error) Code() int { return e.code }
var (
// ErrorCodeString maps Error.Code() to its string representation.
ErrorCodeString = map[int]string{
sqlite3.SQLITE_ABORT: "Callback routine requested an abort (SQLITE_ABORT)",
sqlite3.SQLITE_AUTH: "Authorization denied (SQLITE_AUTH)",
sqlite3.SQLITE_BUSY: "The database file is locked (SQLITE_BUSY)",
sqlite3.SQLITE_CANTOPEN: "Unable to open the database file (SQLITE_CANTOPEN)",
sqlite3.SQLITE_CONSTRAINT: "Abort due to constraint violation (SQLITE_CONSTRAINT)",
sqlite3.SQLITE_CORRUPT: "The database disk image is malformed (SQLITE_CORRUPT)",
sqlite3.SQLITE_DONE: "sqlite3_step() has finished executing (SQLITE_DONE)",
sqlite3.SQLITE_EMPTY: "Internal use only (SQLITE_EMPTY)",
sqlite3.SQLITE_ERROR: "Generic error (SQLITE_ERROR)",
sqlite3.SQLITE_FORMAT: "Not used (SQLITE_FORMAT)",
sqlite3.SQLITE_FULL: "Insertion failed because database is full (SQLITE_FULL)",
sqlite3.SQLITE_INTERNAL: "Internal logic error in SQLite (SQLITE_INTERNAL)",
sqlite3.SQLITE_INTERRUPT: "Operation terminated by sqlite3_interrupt()(SQLITE_INTERRUPT)",
sqlite3.SQLITE_IOERR | (1 << 8): "(SQLITE_IOERR_READ)",
sqlite3.SQLITE_IOERR | (10 << 8): "(SQLITE_IOERR_DELETE)",
sqlite3.SQLITE_IOERR | (11 << 8): "(SQLITE_IOERR_BLOCKED)",
sqlite3.SQLITE_IOERR | (12 << 8): "(SQLITE_IOERR_NOMEM)",
sqlite3.SQLITE_IOERR | (13 << 8): "(SQLITE_IOERR_ACCESS)",
sqlite3.SQLITE_IOERR | (14 << 8): "(SQLITE_IOERR_CHECKRESERVEDLOCK)",
sqlite3.SQLITE_IOERR | (15 << 8): "(SQLITE_IOERR_LOCK)",
sqlite3.SQLITE_IOERR | (16 << 8): "(SQLITE_IOERR_CLOSE)",
sqlite3.SQLITE_IOERR | (17 << 8): "(SQLITE_IOERR_DIR_CLOSE)",
sqlite3.SQLITE_IOERR | (2 << 8): "(SQLITE_IOERR_SHORT_READ)",
sqlite3.SQLITE_IOERR | (3 << 8): "(SQLITE_IOERR_WRITE)",
sqlite3.SQLITE_IOERR | (4 << 8): "(SQLITE_IOERR_FSYNC)",
sqlite3.SQLITE_IOERR | (5 << 8): "(SQLITE_IOERR_DIR_FSYNC)",
sqlite3.SQLITE_IOERR | (6 << 8): "(SQLITE_IOERR_TRUNCATE)",
sqlite3.SQLITE_IOERR | (7 << 8): "(SQLITE_IOERR_FSTAT)",
sqlite3.SQLITE_IOERR | (8 << 8): "(SQLITE_IOERR_UNLOCK)",
sqlite3.SQLITE_IOERR | (9 << 8): "(SQLITE_IOERR_RDLOCK)",
sqlite3.SQLITE_IOERR: "Some kind of disk I/O error occurred (SQLITE_IOERR)",
sqlite3.SQLITE_LOCKED | (1 << 8): "(SQLITE_LOCKED_SHAREDCACHE)",
sqlite3.SQLITE_LOCKED: "A table in the database is locked (SQLITE_LOCKED)",
sqlite3.SQLITE_MISMATCH: "Data type mismatch (SQLITE_MISMATCH)",
sqlite3.SQLITE_MISUSE: "Library used incorrectly (SQLITE_MISUSE)",
sqlite3.SQLITE_NOLFS: "Uses OS features not supported on host (SQLITE_NOLFS)",
sqlite3.SQLITE_NOMEM: "A malloc() failed (SQLITE_NOMEM)",
sqlite3.SQLITE_NOTADB: "File opened that is not a database file (SQLITE_NOTADB)",
sqlite3.SQLITE_NOTFOUND: "Unknown opcode in sqlite3_file_control() (SQLITE_NOTFOUND)",
sqlite3.SQLITE_NOTICE: "Notifications from sqlite3_log() (SQLITE_NOTICE)",
sqlite3.SQLITE_PERM: "Access permission denied (SQLITE_PERM)",
sqlite3.SQLITE_PROTOCOL: "Database lock protocol error (SQLITE_PROTOCOL)",
sqlite3.SQLITE_RANGE: "2nd parameter to sqlite3_bind out of range (SQLITE_RANGE)",
sqlite3.SQLITE_READONLY: "Attempt to write a readonly database (SQLITE_READONLY)",
sqlite3.SQLITE_ROW: "sqlite3_step() has another row ready (SQLITE_ROW)",
sqlite3.SQLITE_SCHEMA: "The database schema changed (SQLITE_SCHEMA)",
sqlite3.SQLITE_TOOBIG: "String or BLOB exceeds size limit (SQLITE_TOOBIG)",
sqlite3.SQLITE_WARNING: "Warnings from sqlite3_log() (SQLITE_WARNING)",
}
)
func init() {
sql.Register(driverName, newDriver())
}
type result struct {
lastInsertID int64
rowsAffected int
}
func newResult(c *conn) (_ *result, err error) {
r := &result{}
if r.rowsAffected, err = c.changes(); err != nil {
return nil, err
}
if r.lastInsertID, err = c.lastInsertRowID(); err != nil {
return nil, err
}
return r, nil
}
// LastInsertId returns the database's auto-generated ID after, for example, an
// INSERT into a table with primary key.
func (r *result) LastInsertId() (int64, error) {
if r == nil {
return 0, nil
}
return r.lastInsertID, nil
}
// RowsAffected returns the number of rows affected by the query.
func (r *result) RowsAffected() (int64, error) {
if r == nil {
return 0, nil
}
return int64(r.rowsAffected), nil
}
type rows struct {
allocs []uintptr
c *conn
columns []string
pstmt uintptr
doStep bool
empty bool
}
func newRows(c *conn, pstmt uintptr, allocs []uintptr, empty bool) (r *rows, err error) {
r = &rows{c: c, pstmt: pstmt, allocs: allocs, empty: empty}
defer func() {
if err != nil {
r.Close()
r = nil
}
}()
n, err := c.columnCount(pstmt)
if err != nil {
return nil, err
}
r.columns = make([]string, n)
for i := range r.columns {
if r.columns[i], err = r.c.columnName(pstmt, i); err != nil {
return nil, err
}
}
return r, nil
}
// Close closes the rows iterator.
func (r *rows) Close() (err error) {
for _, v := range r.allocs {
r.c.free(v)
}
r.allocs = nil
return r.c.finalize(r.pstmt)
}
// Columns returns the names of the columns. The number of columns of the
// result is inferred from the length of the slice. If a particular column name
// isn't known, an empty string should be returned for that entry.
func (r *rows) Columns() (c []string) {
return r.columns
}
// Next is called to populate the next row of data into the provided slice. The
// provided slice will be the same size as the Columns() are wide.
//
// Next should return io.EOF when there are no more rows.
func (r *rows) Next(dest []driver.Value) (err error) {
if r.empty {
return io.EOF
}
rc := sqlite3.SQLITE_ROW
if r.doStep {
if rc, err = r.c.step(r.pstmt); err != nil {
return err
}
}
r.doStep = true
switch rc {
case sqlite3.SQLITE_ROW:
if g, e := len(dest), len(r.columns); g != e {
return fmt.Errorf("sqlite: Next: have %v destination values, expected %v", g, e)
}
for i := range dest {
ct, err := r.c.columnType(r.pstmt, i)
if err != nil {
return err
}
switch ct {
case sqlite3.SQLITE_INTEGER:
v, err := r.c.columnInt64(r.pstmt, i)
if err != nil {
return err
}
dest[i] = v
case sqlite3.SQLITE_FLOAT:
v, err := r.c.columnDouble(r.pstmt, i)
if err != nil {
return err
}
dest[i] = v
case sqlite3.SQLITE_TEXT:
v, err := r.c.columnText(r.pstmt, i)
if err != nil {
return err
}
switch r.ColumnTypeDatabaseTypeName(i) {
case "DATE", "DATETIME", "TIMESTAMP":
dest[i], _ = r.c.parseTime(v)
default:
dest[i] = v
}
case sqlite3.SQLITE_BLOB:
v, err := r.c.columnBlob(r.pstmt, i)
if err != nil {
return err
}
dest[i] = v
case sqlite3.SQLITE_NULL:
dest[i] = nil
default:
return fmt.Errorf("internal error: rc %d", rc)
}
}
return nil
case sqlite3.SQLITE_DONE:
return io.EOF
default:
return r.c.errstr(int32(rc))
}
}
// Inspired by mattn/go-sqlite3: https://github.com/mattn/go-sqlite3/blob/ab91e934/sqlite3.go#L210-L226
//
// These time.Parse formats handle formats 1 through 7 listed at https://www.sqlite.org/lang_datefunc.html.
var parseTimeFormats = []string{
"2006-01-02 15:04:05.999999999-07:00",
"2006-01-02T15:04:05.999999999-07:00",
"2006-01-02 15:04:05.999999999",
"2006-01-02T15:04:05.999999999",
"2006-01-02 15:04",
"2006-01-02T15:04",
"2006-01-02",
}
// Attempt to parse s as a time. Return (s, false) if s is not
// recognized as a valid time encoding.
func (c *conn) parseTime(s string) (interface{}, bool) {
if v, ok := c.parseTimeString(s, strings.Index(s, "m=")); ok {
return v, true
}
ts := strings.TrimSuffix(s, "Z")
for _, f := range parseTimeFormats {
t, err := time.Parse(f, ts)
if err == nil {
return t, true
}
}
return s, false
}
// Attempt to parse s as a time string produced by t.String(). If x > 0 it's
// the index of substring "m=" within s. Return (s, false) if s is
// not recognized as a valid time encoding.
func (c *conn) parseTimeString(s0 string, x int) (interface{}, bool) {
s := s0
if x > 0 {
s = s[:x] // "2006-01-02 15:04:05.999999999 -0700 MST m=+9999" -> "2006-01-02 15:04:05.999999999 -0700 MST "
}
s = strings.TrimSpace(s)
if t, err := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", s); err == nil {
return t, true
}
return s0, false
}
// writeTimeFormats are the names and formats supported
// by the `_time_format` DSN query param.
var writeTimeFormats = map[string]string{
"sqlite": parseTimeFormats[0],
}
func (c *conn) formatTime(t time.Time) string {
// Before configurable write time formats were supported,
// time.Time.String was used. Maintain that default to
// keep existing driver users formatting times the same.
if c.writeTimeFormat == "" {
return t.String()
}
return t.Format(c.writeTimeFormat)
}
// RowsColumnTypeDatabaseTypeName may be implemented by Rows. It should return
// the database system type name without the length. Type names should be
// uppercase. Examples of returned types: "VARCHAR", "NVARCHAR", "VARCHAR2",
// "CHAR", "TEXT", "DECIMAL", "SMALLINT", "INT", "BIGINT", "BOOL", "[]BIGINT",
// "JSONB", "XML", "TIMESTAMP".
func (r *rows) ColumnTypeDatabaseTypeName(index int) string {
return strings.ToUpper(r.c.columnDeclType(r.pstmt, index))
}
// RowsColumnTypeLength may be implemented by Rows. It should return the length
// of the column type if the column is a variable length type. If the column is
// not a variable length type ok should return false. If length is not limited
// other than system limits, it should return math.MaxInt64. The following are
// examples of returned values for various types:
//
// TEXT (math.MaxInt64, true)
// varchar(10) (10, true)
// nvarchar(10) (10, true)
// decimal (0, false)
// int (0, false)
// bytea(30) (30, true)
func (r *rows) ColumnTypeLength(index int) (length int64, ok bool) {
t, err := r.c.columnType(r.pstmt, index)
if err != nil {
return 0, false
}
switch t {
case sqlite3.SQLITE_INTEGER:
return 0, false
case sqlite3.SQLITE_FLOAT:
return 0, false
case sqlite3.SQLITE_TEXT:
return math.MaxInt64, true
case sqlite3.SQLITE_BLOB:
return math.MaxInt64, true
case sqlite3.SQLITE_NULL:
return 0, false
default:
return 0, false
}
}
// RowsColumnTypeNullable may be implemented by Rows. The nullable value should
// be true if it is known the column may be null, or false if the column is
// known to be not nullable. If the column nullability is unknown, ok should be
// false.
func (r *rows) ColumnTypeNullable(index int) (nullable, ok bool) {
return true, true
}
// RowsColumnTypePrecisionScale may be implemented by Rows. It should return
// the precision and scale for decimal types. If not applicable, ok should be
// false. The following are examples of returned values for various types:
//
// decimal(38, 4) (38, 4, true)
// int (0, 0, false)
// decimal (math.MaxInt64, math.MaxInt64, true)
func (r *rows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) {
return 0, 0, false
}
// RowsColumnTypeScanType may be implemented by Rows. It should return the
// value type that can be used to scan types into. For example, the database
// column type "bigint" this should return "reflect.TypeOf(int64(0))".
func (r *rows) ColumnTypeScanType(index int) reflect.Type {
t, err := r.c.columnType(r.pstmt, index)
if err != nil {
return reflect.TypeOf("")
}
switch t {
case sqlite3.SQLITE_INTEGER:
switch strings.ToLower(r.c.columnDeclType(r.pstmt, index)) {
case "boolean":
return reflect.TypeOf(false)
case "date", "datetime", "time", "timestamp":
return reflect.TypeOf(time.Time{})
default:
return reflect.TypeOf(int64(0))
}
case sqlite3.SQLITE_FLOAT:
return reflect.TypeOf(float64(0))
case sqlite3.SQLITE_TEXT:
return reflect.TypeOf("")
case sqlite3.SQLITE_BLOB:
return reflect.TypeOf([]byte(nil))
case sqlite3.SQLITE_NULL:
return reflect.TypeOf(nil)
default:
return reflect.TypeOf("")
}
}
type stmt struct {
c *conn
psql uintptr
}
func newStmt(c *conn, sql string) (*stmt, error) {
p, err := libc.CString(sql)
if err != nil {
return nil, err
}
stm := stmt{c: c, psql: p}
return &stm, nil
}
// Close closes the statement.
//
// As of Go 1.1, a Stmt will not be closed if it's in use by any queries.
func (s *stmt) Close() (err error) {
s.c.free(s.psql)
s.psql = 0
return nil
}
// Exec executes a query that doesn't return rows, such as an INSERT or UPDATE.
//
// Deprecated: Drivers should implement StmtExecContext instead (or
// additionally).
func (s *stmt) Exec(args []driver.Value) (driver.Result, error) { //TODO StmtExecContext
return s.exec(context.Background(), toNamedValues(args))
}
// toNamedValues converts []driver.Value to []driver.NamedValue
func toNamedValues(vals []driver.Value) (r []driver.NamedValue) {
r = make([]driver.NamedValue, len(vals))
for i, val := range vals {
r[i] = driver.NamedValue{Value: val, Ordinal: i + 1}
}
return r
}
func (s *stmt) exec(ctx context.Context, args []driver.NamedValue) (r driver.Result, err error) {
var pstmt uintptr
var done int32
if ctx != nil {
if ctxDone := ctx.Done(); ctxDone != nil {
select {
case <-ctxDone:
return nil, ctx.Err()
default:
}
defer interruptOnDone(ctx, s.c, &done)()
}
}
defer func() {
if pstmt != 0 {
// ensure stmt finalized.
e := s.c.finalize(pstmt)
if err == nil && e != nil {
// prioritize original
// returned error.
err = e
}
}
if ctx != nil && atomic.LoadInt32(&done) != 0 {
r, err = nil, ctx.Err()
}
}()
for psql := s.psql; *(*byte)(unsafe.Pointer(psql)) != 0 && atomic.LoadInt32(&done) == 0; {
if pstmt, err = s.c.prepareV2(&psql); err != nil {
return nil, err
}
if pstmt == 0 {
continue
}
err = func() (err error) {
n, err := s.c.bindParameterCount(pstmt)
if err != nil {
return err
}
if n != 0 {
allocs, err := s.c.bind(pstmt, n, args)
if err != nil {
return err
}
if len(allocs) != 0 {
defer func() {
for _, v := range allocs {
s.c.free(v)
}
}()
}
}
rc, err := s.c.step(pstmt)
if err != nil {
return err
}
switch rc & 0xff {
case sqlite3.SQLITE_DONE, sqlite3.SQLITE_ROW:
r, err = newResult(s.c)
default:
return s.c.errstr(int32(rc))
}
return nil
}()
e := s.c.finalize(pstmt)
pstmt = 0 // done with
if err == nil && e != nil {
// prioritize original
// returned error.
err = e
}
if err != nil {
return nil, err
}
}
return r, err
}
// NumInput returns the number of placeholder parameters.
//
// If NumInput returns >= 0, the sql package will sanity check argument counts
// from callers and return errors to the caller before the statement's Exec or
// Query methods are called.
//
// NumInput may also return -1, if the driver doesn't know its number of
// placeholders. In that case, the sql package will not sanity check Exec or
// Query argument counts.
func (s *stmt) NumInput() (n int) {
return -1
}
// Query executes a query that may return rows, such as a
// SELECT.
//
// Deprecated: Drivers should implement StmtQueryContext instead (or
// additionally).
func (s *stmt) Query(args []driver.Value) (driver.Rows, error) { //TODO StmtQueryContext
return s.query(context.Background(), toNamedValues(args))
}
func (s *stmt) query(ctx context.Context, args []driver.NamedValue) (r driver.Rows, err error) {
var pstmt uintptr
var done int32
if ctx != nil {
if ctxDone := ctx.Done(); ctxDone != nil {
select {
case <-ctxDone:
return nil, ctx.Err()
default:
}
defer interruptOnDone(ctx, s.c, &done)()
}
}
var allocs []uintptr
defer func() {
if pstmt != 0 {
// ensure stmt finalized.
e := s.c.finalize(pstmt)
if err == nil && e != nil {
// prioritize original
// returned error.
err = e
}
}
if ctx != nil && atomic.LoadInt32(&done) != 0 {
r, err = nil, ctx.Err()
} else if r == nil && err == nil {
r, err = newRows(s.c, pstmt, allocs, true)
}
}()
for psql := s.psql; *(*byte)(unsafe.Pointer(psql)) != 0 && atomic.LoadInt32(&done) == 0; {
if pstmt, err = s.c.prepareV2(&psql); err != nil {
return nil, err
}
if pstmt == 0 {
continue
}
err = func() (err error) {
n, err := s.c.bindParameterCount(pstmt)
if err != nil {
return err
}
if n != 0 {
if allocs, err = s.c.bind(pstmt, n, args); err != nil {
return err
}
}
rc, err := s.c.step(pstmt)
if err != nil {
return err
}
switch rc & 0xff {
case sqlite3.SQLITE_ROW:
if r != nil {
r.Close()
}
if r, err = newRows(s.c, pstmt, allocs, false); err != nil {
return err
}
pstmt = 0
return nil
case sqlite3.SQLITE_DONE:
if r == nil {
if r, err = newRows(s.c, pstmt, allocs, true); err != nil {
return err
}
pstmt = 0
return nil
}
// nop
default:
return s.c.errstr(int32(rc))
}
if *(*byte)(unsafe.Pointer(psql)) == 0 {
if r != nil {
r.Close()
}
if r, err = newRows(s.c, pstmt, allocs, true); err != nil {
return err
}
pstmt = 0
}
return nil
}()
e := s.c.finalize(pstmt)
pstmt = 0 // done with
if err == nil && e != nil {
// prioritize original
// returned error.
err = e
}
if err != nil {
return nil, err
}
}
return r, err
}
type tx struct {
c *conn
}
func newTx(ctx context.Context, c *conn, opts driver.TxOptions) (*tx, error) {
r := &tx{c: c}
sql := "begin"
if !opts.ReadOnly && c.beginMode != "" {
sql = "begin " + c.beginMode
}
if err := r.exec(ctx, sql); err != nil {
return nil, err
}
return r, nil
}
// Commit implements driver.Tx.
func (t *tx) Commit() (err error) {
return t.exec(context.Background(), "commit")
}
// Rollback implements driver.Tx.
func (t *tx) Rollback() (err error) {
return t.exec(context.Background(), "rollback")
}
func (t *tx) exec(ctx context.Context, sql string) (err error) {
psql, err := libc.CString(sql)
if err != nil {
return err
}
defer t.c.free(psql)
//TODO use t.conn.ExecContext() instead
if ctx != nil && ctx.Done() != nil {
defer interruptOnDone(ctx, t.c, nil)()
}
if rc := sqlite3.Xsqlite3_exec(t.c.tls, t.c.db, psql, 0, 0, 0); rc != sqlite3.SQLITE_OK {
return t.c.errstr(rc)
}
return nil
}
// interruptOnDone sets up a goroutine to interrupt the provided db when the
// context is canceled, and returns a function the caller must defer so it
// doesn't interrupt after the caller finishes.
func interruptOnDone(
ctx context.Context,
c *conn,
done *int32,
) func() {
if done == nil {
var d int32
done = &d
}
donech := make(chan struct{})
go func() {
select {
case <-ctx.Done():
// don't call interrupt if we were already done: it indicates that this
// call to exec is no longer running and we would be interrupting
// nothing, or even possibly an unrelated later call to exec.
if atomic.AddInt32(done, 1) == 1 {
c.interrupt(c.db)
}
case <-donech:
}
}()
// the caller is expected to defer this function
return func() {
// set the done flag so that a context cancellation right after the caller
// returns doesn't trigger a call to interrupt for some other statement.
atomic.AddInt32(done, 1)
close(donech)
}
}
type conn struct {
db uintptr // *sqlite3.Xsqlite3
tls *libc.TLS
// Context handling can cause conn.Close and conn.interrupt to be invoked
// concurrently.
sync.Mutex
writeTimeFormat string
beginMode string
}
func newConn(dsn string) (*conn, error) {
var query, vfsName string
// Parse the query parameters from the dsn and them from the dsn if not prefixed by file:
// https://github.com/mattn/go-sqlite3/blob/3392062c729d77820afc1f5cae3427f0de39e954/sqlite3.go#L1046
// https://github.com/mattn/go-sqlite3/blob/3392062c729d77820afc1f5cae3427f0de39e954/sqlite3.go#L1383
pos := strings.IndexRune(dsn, '?')
if pos >= 1 {
query = dsn[pos+1:]
var err error
vfsName, err = getVFSName(query)
if err != nil {
return nil, err
}
if !strings.HasPrefix(dsn, "file:") {
dsn = dsn[:pos]
}
}
c := &conn{tls: libc.NewTLS()}
db, err := c.openV2(
dsn,
vfsName,
sqlite3.SQLITE_OPEN_READWRITE|sqlite3.SQLITE_OPEN_CREATE|
sqlite3.SQLITE_OPEN_FULLMUTEX|
sqlite3.SQLITE_OPEN_URI,
)
if err != nil {
return nil, err
}
c.db = db
if err = c.extendedResultCodes(true); err != nil {
c.Close()
return nil, err
}
if err = applyQueryParams(c, query); err != nil {
c.Close()
return nil, err
}
return c, nil
}
func getVFSName(query string) (r string, err error) {
q, err := url.ParseQuery(query)
if err != nil {
return "", err
}
for _, v := range q["vfs"] {
if r != "" && r != v {
return "", fmt.Errorf("conflicting vfs query parameters: %v", q["vfs"])
}
r = v
}
return r, nil
}
func applyQueryParams(c *conn, query string) error {
q, err := url.ParseQuery(query)
if err != nil {
return err
}
for _, v := range q["_pragma"] {
cmd := "pragma " + v
_, err := c.exec(context.Background(), cmd, nil)
if err != nil {
return err
}
}
if v := q.Get("_time_format"); v != "" {
f, ok := writeTimeFormats[v]
if !ok {
return fmt.Errorf("unknown _time_format %q", v)
}
c.writeTimeFormat = f
}
if v := q.Get("_txlock"); v != "" {
lower := strings.ToLower(v)
if lower != "deferred" && lower != "immediate" && lower != "exclusive" {
return fmt.Errorf("unknown _txlock %q", v)
}
c.beginMode = v
}
return nil
}
// C documentation
//
// const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
func (c *conn) columnBlob(pstmt uintptr, iCol int) (v []byte, err error) {
p := sqlite3.Xsqlite3_column_blob(c.tls, pstmt, int32(iCol))
len, err := c.columnBytes(pstmt, iCol)
if err != nil {
return nil, err
}
if p == 0 || len == 0 {
return nil, nil
}
v = make([]byte, len)
copy(v, (*libc.RawMem)(unsafe.Pointer(p))[:len:len])
return v, nil
}
// C documentation
//
// int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
func (c *conn) columnBytes(pstmt uintptr, iCol int) (_ int, err error) {
v := sqlite3.Xsqlite3_column_bytes(c.tls, pstmt, int32(iCol))
return int(v), nil
}
// C documentation
//
// const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
func (c *conn) columnText(pstmt uintptr, iCol int) (v string, err error) {
p := sqlite3.Xsqlite3_column_text(c.tls, pstmt, int32(iCol))
len, err := c.columnBytes(pstmt, iCol)
if err != nil {
return "", err
}
if p == 0 || len == 0 {
return "", nil
}
b := make([]byte, len)
copy(b, (*libc.RawMem)(unsafe.Pointer(p))[:len:len])
return string(b), nil
}
// C documentation
//
// double sqlite3_column_double(sqlite3_stmt*, int iCol);
func (c *conn) columnDouble(pstmt uintptr, iCol int) (v float64, err error) {
v = sqlite3.Xsqlite3_column_double(c.tls, pstmt, int32(iCol))
return v, nil
}
// C documentation
//
// sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
func (c *conn) columnInt64(pstmt uintptr, iCol int) (v int64, err error) {
v = sqlite3.Xsqlite3_column_int64(c.tls, pstmt, int32(iCol))
return v, nil
}
// C documentation
//
// int sqlite3_column_type(sqlite3_stmt*, int iCol);
func (c *conn) columnType(pstmt uintptr, iCol int) (_ int, err error) {
v := sqlite3.Xsqlite3_column_type(c.tls, pstmt, int32(iCol))
return int(v), nil
}
// C documentation
//
// const char *sqlite3_column_decltype(sqlite3_stmt*,int);
func (c *conn) columnDeclType(pstmt uintptr, iCol int) string {
return libc.GoString(sqlite3.Xsqlite3_column_decltype(c.tls, pstmt, int32(iCol)))
}
// C documentation
//
// const char *sqlite3_column_name(sqlite3_stmt*, int N);
func (c *conn) columnName(pstmt uintptr, n int) (string, error) {
p := sqlite3.Xsqlite3_column_name(c.tls, pstmt, int32(n))
return libc.GoString(p), nil
}
// C documentation
//