This repository was archived by the owner on Jan 6, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathconnection.go
More file actions
675 lines (602 loc) · 16.5 KB
/
connection.go
File metadata and controls
675 lines (602 loc) · 16.5 KB
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
package turso_go
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/ebitengine/purego"
)
func init() {
err := ensureLibLoaded()
if err != nil {
panic(err)
}
sql.Register(driverName, &tursoDriver{})
}
/**
* Driver is the interface that must be implemented by a database
* driver.
*
* Database drivers may implement [DriverContext] for access
* to contexts and to parse the name only once for a pool of connections,
* instead of once per connection.
**/
type tursoDriver struct {
sync.Mutex
}
var (
libOnce sync.Once
tursoLib uintptr
loadErr error
dbOpen func(string) uintptr
dbClose func(uintptr)
stmtLastInsertId func(uintptr, uintptr) int32
connPrepare func(uintptr, string, uint64) uintptr
connGetError func(uintptr) uintptr
stmtChanges func(uintptr, uintptr) int32
stmtReset func(uintptr) int32
rowsGetColumnType func(uintptr, int32) uintptr
freeBlobFunc func(uintptr)
freeStringFunc func(uintptr)
rowsGetColumns func(uintptr) int32
rowsGetColumnName func(uintptr, int32) uintptr
rowsGetValue func(uintptr, uint64) uintptr
rowsGetError func(uintptr) uintptr
closeRows func(uintptr)
rowsNext func(uintptr) int32
stmtQuery func(stmtPtr uintptr, argsPtr uintptr, argCount uint64, timeoutMs uint64) uintptr
stmtExec func(stmtPtr uintptr, argsPtr uintptr, argCount uint64, changes uintptr, timeoutMs uint64) int32
stmtParamCount func(uintptr) int32
stmtGetError func(uintptr) uintptr
stmtClose func(uintptr) int32
dbPing func(uintptr) int32
)
// Register all the symbols on library load
func ensureLibLoaded() error {
libOnce.Do(func() {
tursoLib, loadErr = loadLibrary()
if loadErr != nil {
return
}
purego.RegisterLibFunc(&dbOpen, tursoLib, FfiDbOpen)
purego.RegisterLibFunc(&dbClose, tursoLib, FfiDbClose)
purego.RegisterLibFunc(&dbPing, tursoLib, FfiDbPing)
purego.RegisterLibFunc(&connPrepare, tursoLib, FfiDbPrepare)
purego.RegisterLibFunc(&connGetError, tursoLib, FfiDbGetError)
purego.RegisterLibFunc(&freeBlobFunc, tursoLib, FfiFreeBlob)
purego.RegisterLibFunc(&stmtLastInsertId, tursoLib, FfiConnLastInsertId)
purego.RegisterLibFunc(&stmtChanges, tursoLib, FfiConnChanges)
purego.RegisterLibFunc(&stmtReset, tursoLib, FfiStmtReset)
purego.RegisterLibFunc(&rowsGetColumnType, tursoLib, FfiRowsGetColumnType)
purego.RegisterLibFunc(&freeStringFunc, tursoLib, FfiFreeCString)
purego.RegisterLibFunc(&rowsGetColumns, tursoLib, FfiRowsGetColumns)
purego.RegisterLibFunc(&rowsGetColumnName, tursoLib, FfiRowsGetColumnName)
purego.RegisterLibFunc(&rowsGetValue, tursoLib, FfiRowsGetValue)
purego.RegisterLibFunc(&closeRows, tursoLib, FfiRowsClose)
purego.RegisterLibFunc(&rowsNext, tursoLib, FfiRowsNext)
purego.RegisterLibFunc(&rowsGetError, tursoLib, FfiRowsGetError)
purego.RegisterLibFunc(&stmtQuery, tursoLib, FfiStmtQuery)
purego.RegisterLibFunc(&stmtExec, tursoLib, FfiStmtExec)
purego.RegisterLibFunc(&stmtParamCount, tursoLib, FfiStmtParameterCount)
purego.RegisterLibFunc(&stmtGetError, tursoLib, FfiStmtGetError)
purego.RegisterLibFunc(&stmtClose, tursoLib, FfiStmtClose)
})
return loadErr
}
// database/sql driver.go 110
/**
* A Connector represents a driver in a fixed configuration
* and can create any number of equivalent Conns for use
* by multiple goroutines.
*
* A Connector can be passed to [database/sql.OpenDB], to allow drivers
* to implement their own [database/sql.DB] constructors, or returned by
* [DriverContext]'s OpenConnector method, to allow drivers
* access to context and to avoid repeated parsing of driver
* configuration.
*
* If a Connector implements [io.Closer], the [database/sql.DB.Close]
* method will call the Close method and return error (if any).
**/
type tursoConnector struct {
dsn string
}
// database/sql driver.go 123
/**
* Connect returns a connection to the database.
* Connect may return a cached connection (one previously
* closed), but doing so is unnecessary; the sql package
* maintains a pool of idle connections for efficient re-use.
*
* The provided context.Context is for dialing purposes only
* (see net.DialContext) and should not be stored or used for
* other purposes. A default timeout should still be used
* when dialing as a connection pool may call Connect
* asynchronously to any query.
*
* The returned connection is only used by one goroutine at a
* time.
**/
func (c *tursoConnector) Connect(ctx context.Context) (driver.Conn, error) {
conn, err := openConn(c.dsn)
if err != nil {
return nil, err
}
return conn, nil
}
// database/sql driver.go
/**
* If a [Driver] implements DriverContext, then [database/sql.DB] will call
* OpenConnector to obtain a [Connector] and then invoke
* that [Connector]'s Connect method to obtain each needed connection,
* instead of invoking the [Driver]'s Open method for each connection.
* The two-step sequence allows drivers to parse the name just once
* and also provides access to per-[Conn] contexts.
**/
func (c *tursoConnector) Driver() driver.Driver {
return &tursoDriver{}
}
func (d *tursoDriver) OpenConnector(name string) (driver.Connector, error) {
return &tursoConnector{dsn: name}, nil
}
// database/sql driver.go 86
/**
* Open returns a new connection to the database.
* The name is a string in a driver-specific format.
*
* Open may return a cached connection (one previously
* closed), but doing so is unnecessary; the sql package
* maintains a pool of idle connections for efficient re-use.
*
* The returned connection is only used by one goroutine at a
* time.
**/
func (d *tursoDriver) Open(name string) (driver.Conn, error) {
d.Lock()
conn, err := openConn(name)
d.Unlock()
if err != nil {
return nil, err
}
return conn, nil
}
// database/sql driver.go 230
/**
* Conn is a connection to a database. It is not used concurrently
* by multiple goroutines.
*
* Conn is assumed to be stateful.
**/
type tursoConn struct {
mu sync.Mutex
ctx uintptr
closed bool
}
func openConn(dsn string) (*tursoConn, error) {
ctx := dbOpen(dsn)
if ctx == 0 {
return nil, fmt.Errorf("failed to open database for dsn=%q", dsn)
}
conn := &tursoConn{
mu: sync.Mutex{},
ctx: ctx,
closed: false,
}
return conn, loadErr
}
// database/sql driver.go 165
/**
* Pinger is an optional interface that may be implemented by a [Conn].
*
* If a [Conn] does not implement Pinger, the [database/sql.DB.Ping] and
* [database/sql.DB.PingContext] will check if there is at least one [Conn] available.
*
* If Conn.Ping returns [ErrBadConn], [database/sql.DB.Ping] and [database/sql.DB.PingContext] will remove
* the [Conn] from pool.
**/
func (c *tursoConn) Ping(ctx context.Context) error {
if c.ctx == 0 || c.closed {
return driver.ErrBadConn // Important: signals pool to remove connection
}
select {
case <-ctx.Done():
return ctx.Err()
default:
}
c.mu.Lock()
res := ResultCode(dbPing(c.ctx))
c.mu.Unlock()
if res != Ok {
return driver.ErrBadConn // Not just an error - must be ErrBadConn
}
return nil
}
// database/sql driver.go 305
/**
* Validator may be implemented by [Conn] to allow drivers to
* signal if a connection is valid or if it should be discarded.
**/
func (c *tursoConn) IsValid() bool {
return c.ctx != 0 && !c.closed
}
// database/sql driver.go 296
/**
* SessionResetter may be implemented by [Conn] to allow drivers to reset the
* session state associated with the connection and to signal a bad connection.
**/
func (c *tursoConn) ResetSession(ctx context.Context) error {
if !c.IsValid() {
return driver.ErrBadConn
}
c.mu.Lock()
defer c.mu.Unlock()
// Rollback any pending transaction
stmtPtr := connPrepare(c.ctx, "ROLLBACK", 0)
if stmtPtr != 0 {
stmt := newStmt(stmtPtr, "ROLLBACK")
stmt.Exec(nil)
stmt.Close()
}
pragma := "PRAGMA foreign_keys=OFF"
stmtPtr = connPrepare(c.ctx, pragma, 0)
if stmtPtr != 0 {
stmt := newStmt(stmtPtr, pragma)
stmt.Exec(nil)
stmt.Close()
}
return nil
}
// database/sql driver.go 249
/**
* Close invalidates and potentially stops any current
* prepared statements and transactions, marking this
* connection as no longer in use.
*
* Because the sql package maintains a free pool of
* connections and only calls Close when there's a surplus of
* idle connections, it shouldn't be necessary for drivers to
* do their own connection caching.
*
* Drivers must ensure all network calls made by Close
* do not block indefinitely (e.g. apply a timeout).
**/
func (c *tursoConn) Close() error {
if c.ctx == 0 {
return nil
}
c.mu.Lock()
dbClose(c.ctx)
c.mu.Unlock()
c.ctx = 0
c.closed = true
return nil
}
func (c *tursoConn) getError() error {
if c.ctx == 0 {
return errors.New("connection closed")
}
err := connGetError(c.ctx)
if err == 0 {
return nil
}
defer freeStringFunc(err)
cpy := fmt.Sprintf("%s", GoString(err))
return errors.New(cpy)
}
var errNoLastInsertID = errors.New("no LastInsertId available")
type tursoResult struct {
lastID int64
rows int64
haveLast bool
}
// database/sql driver.go 316
/**
* Result is the result of a query execution.
**/
var _ driver.Result = tursoResult{}
func (r tursoResult) LastInsertId() (int64, error) {
if !r.haveLast {
return 0, errNoLastInsertID
}
return r.lastID, nil
}
func (r tursoResult) RowsAffected() (int64, error) {
return r.rows, nil
}
// database/sql driver.go 257
/**
* ConnPrepareContext enhances the [Conn] interface with context.
* PrepareContext returns a prepared statement, bound to this connection.
* context is for the preparation of the statement,
* it must not store the context within the statement itself.
**/
func (c *tursoConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
if c.ctx == 0 {
return nil, errors.New("connection closed")
}
c.mu.Lock()
stmtPtr := connPrepare(c.ctx, query, getTimeoutMs(ctx))
c.mu.Unlock()
if stmtPtr == 0 {
return nil, c.getError()
}
stmt := newStmt(stmtPtr, query)
return stmt, nil
}
// database/sql driver.go 236
/**
* Prepare returns a prepared statement, bound to this connection.
**/
func (c *tursoConn) Prepare(query string) (driver.Stmt, error) {
if c.ctx == 0 {
return nil, errors.New("connection closed")
}
c.mu.Lock()
stmtPtr := connPrepare(c.ctx, query, 0)
c.mu.Unlock()
if stmtPtr == 0 {
return nil, c.getError()
}
return newStmt(stmtPtr, query), nil
}
// database/sql driver.go 518
// Tx is a transaction.
// tursoTx implements driver.Tx
type tursoTx struct {
conn *tursoConn
}
// Begin starts a new transaction with default isolation level
func (c *tursoConn) Begin() (driver.Tx, error) {
if c.ctx == 0 {
return nil, errors.New("connection closed")
}
// Execute BEGIN statement
c.mu.Lock()
stmtPtr := connPrepare(c.ctx, "BEGIN", 0)
c.mu.Unlock()
if stmtPtr == 0 {
return nil, c.getError()
}
stmt := newStmt(stmtPtr, "BEGIN")
defer stmt.Close()
_, err := stmt.Exec(nil)
if err != nil {
return nil, err
}
return &tursoTx{conn: c}, nil
}
// BeginTx starts a transaction with the specified options.
// Currently only supports default isolation level and non-read-only transactions.
func (c *tursoConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
// Skip handling non-default isolation levels and read-only mode
// for now, letting database/sql package handle these cases
if opts.Isolation != driver.IsolationLevel(sql.LevelDefault) || opts.ReadOnly {
return nil, driver.ErrSkip
}
// Check for context cancellation
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
return c.Begin()
}
}
// Commit commits the transaction
func (tx *tursoTx) Commit() error {
if tx.conn.ctx == 0 {
return errors.New("connection closed")
}
tx.conn.mu.Lock()
stmtPtr := connPrepare(tx.conn.ctx, "COMMIT", 0)
tx.conn.mu.Unlock()
if stmtPtr == 0 {
return tx.conn.getError()
}
stmt := newStmt(stmtPtr, "COMMIT")
defer stmt.Close()
_, err := stmt.Exec(nil)
if err != nil {
if connErr := tx.conn.getError(); connErr != nil {
err = connErr
}
}
return err
}
// Rollback aborts the transaction.
func (tx *tursoTx) Rollback() error {
if tx.conn.ctx == 0 {
return errors.New("connection closed")
}
tx.conn.mu.Lock()
stmtPtr := connPrepare(tx.conn.ctx, "ROLLBACK", 0)
tx.conn.mu.Unlock()
if stmtPtr == 0 {
return tx.conn.getError()
}
stmt := newStmt(stmtPtr, "ROLLBACK")
defer stmt.Close()
_, err := stmt.Exec(nil)
return err
}
// Returns the timeout in milliseconds from the context deadline, or a default of 5000ms if no deadline is set
func getTimeoutMs(ctx context.Context) uint64 {
deadline, ok := ctx.Deadline()
if !ok {
return 5000 // Default 5 second timeout
}
remaining := time.Until(deadline)
if remaining <= 0 {
return 0 // Already expired
}
ms := remaining.Milliseconds()
return uint64(ms)
}
// Returns a merged context with the earlier deadline between the statement's context and the provided context
func (ls *tursoStmt) mergeContexts(ctx context.Context) context.Context {
// If statement has no context, use the provided one
if ls.ctx == nil {
return ctx
}
// If provided context has no deadline, use statement's
execDeadline, execHasDeadline := ctx.Deadline()
if !execHasDeadline {
return ls.ctx
}
// If statement context has no deadline, use provided
stmtDeadline, stmtHasDeadline := ls.ctx.Deadline()
if !stmtHasDeadline {
return ctx
}
// Use the earlier deadline
if execDeadline.Before(stmtDeadline) {
return ctx
}
return ls.ctx
}
// ExecContext handles multi-statement execution when no parameters are provided.
// With parameters, it returns driver.ErrSkip to let database/sql use Prepare/Exec.
// Note: multi-statement execution is not atomic. Use explicit transactions for atomicity.
func (c *tursoConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
if c.ctx == 0 {
return nil, errors.New("connection closed")
}
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
stmts := splitMultiStatements(query)
if len(stmts) == 0 {
return tursoResult{}, nil
}
if len(args) > 0 {
if len(stmts) == 1 {
return nil, driver.ErrSkip
}
return nil, fmt.Errorf("parameters with multiple SQL statements are not supported; split the query and execute separately")
}
timeoutMs := getTimeoutMs(ctx)
var totalChanges, lastID int64
var haveLast bool
for i, sql := range stmts {
if strings.TrimSpace(sql) == "" {
continue
}
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
c.mu.Lock()
stmtPtr := connPrepare(c.ctx, sql, timeoutMs)
c.mu.Unlock()
if stmtPtr == 0 {
return nil, c.getError()
}
stmt := newStmt(stmtPtr, sql)
res, err := stmt.Exec(nil)
stmt.Close()
if err != nil {
if len(stmts) > 1 {
return nil, fmt.Errorf("statement %d of %d failed: %w", i+1, len(stmts), err)
}
return nil, err
}
if rows, _ := res.RowsAffected(); rows > 0 {
totalChanges += rows
}
if id, err := res.LastInsertId(); err == nil {
lastID = id
haveLast = true
}
}
return tursoResult{lastID: lastID, rows: totalChanges, haveLast: haveLast}, nil
}
// splitMultiStatements splits SQL by semicolons, respecting string literals and comments.
// Handles SQL standard escaped quotes ('O”Brien') but not all dialect-specific escapes.
func splitMultiStatements(sql string) []string {
var (
stmts []string
cur strings.Builder
inStr, inIdent bool
inLine, inBlock bool
)
for i := 0; i < len(sql); i++ {
c := sql[i]
next := byte(0)
if i+1 < len(sql) {
next = sql[i+1]
}
if inLine {
cur.WriteByte(c)
if c == '\n' {
inLine = false
}
continue
}
if inBlock {
cur.WriteByte(c)
if c == '*' && next == '/' {
inBlock = false
i++
cur.WriteByte('/')
}
continue
}
if !inStr && !inIdent {
if c == '-' && next == '-' {
inLine = true
cur.WriteString("--")
i++
continue
}
if c == '/' && next == '*' {
inBlock = true
cur.WriteString("/*")
i++
continue
}
}
if c == '\'' && !inIdent {
cur.WriteByte(c)
if inStr && next == '\'' {
i++
cur.WriteByte('\'')
} else {
inStr = !inStr
}
continue
}
if c == '"' && !inStr {
cur.WriteByte(c)
if inIdent && next == '"' {
i++
cur.WriteByte('"')
} else {
inIdent = !inIdent
}
continue
}
if c == ';' && !inStr && !inIdent {
if s := strings.TrimSpace(cur.String()); s != "" {
stmts = append(stmts, s)
}
cur.Reset()
continue
}
cur.WriteByte(c)
}
if s := strings.TrimSpace(cur.String()); s != "" {
stmts = append(stmts, s)
}
return stmts
}