-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstoolap.go
More file actions
1206 lines (1107 loc) · 30.7 KB
/
stoolap.go
File metadata and controls
1206 lines (1107 loc) · 30.7 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
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 2025 Stoolap Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package stoolap
import (
"context"
"database/sql"
"encoding/binary"
"errors"
"math"
"runtime"
"strings"
"sync"
"time"
"unsafe"
)
var errDBClosed = errors.New("stoolap: database is closed")
var errRowsClosed = errors.New("stoolap: rows are closed")
var errStmtClosed = errors.New("stoolap: statement is closed")
var errTxDone = errors.New("stoolap: transaction has already been committed or rolled back")
var errColumnCount = errors.New("stoolap: scan destination count does not match column count")
var errUnsupportedDest = errors.New("stoolap: unsupported scan destination type")
// ErrorCode categorizes stoolap engine errors.
type ErrorCode int
const (
// ErrGeneral is the default code for uncategorized errors.
ErrGeneral ErrorCode = iota
// ErrUniqueConstraint indicates a unique index constraint violation.
ErrUniqueConstraint
// ErrPrimaryKeyConstraint indicates a primary key constraint violation.
ErrPrimaryKeyConstraint
// ErrNotNullConstraint indicates a NOT NULL constraint violation.
ErrNotNullConstraint
// ErrCheckConstraint indicates a CHECK constraint violation.
ErrCheckConstraint
// ErrForeignKeyViolation indicates a foreign key constraint violation.
ErrForeignKeyViolation
// ErrTableNotFound indicates the referenced table does not exist.
ErrTableNotFound
// ErrTableExists indicates the table already exists.
ErrTableExists
)
// Error is a stoolap engine error with a categorized error code.
// Use errors.As to extract it:
//
// var stErr *stoolap.Error
// if errors.As(err, &stErr) {
// switch stErr.Code() {
// case stoolap.ErrUniqueConstraint:
// // handle duplicate
// }
// }
type Error struct {
msg string
code ErrorCode
}
func (e *Error) Error() string { return e.msg }
func (e *Error) Code() ErrorCode { return e.code }
// IsConstraintViolation reports whether the error is any kind of constraint violation
// (unique, primary key, not null, check, or foreign key).
func (e *Error) IsConstraintViolation() bool {
return e.code >= ErrUniqueConstraint && e.code <= ErrForeignKeyViolation
}
func newError(msg string) error {
return &Error{msg: msg, code: classifyError(msg)}
}
func classifyError(msg string) ErrorCode {
if strings.HasPrefix(msg, "unique constraint failed") {
return ErrUniqueConstraint
}
if strings.HasPrefix(msg, "primary key constraint failed") {
return ErrPrimaryKeyConstraint
}
if strings.HasPrefix(msg, "not null constraint failed") {
return ErrNotNullConstraint
}
if strings.HasPrefix(msg, "CHECK constraint failed") {
return ErrCheckConstraint
}
if strings.HasPrefix(msg, "foreign key constraint violation") {
return ErrForeignKeyViolation
}
if strings.HasPrefix(msg, "table '") || strings.HasPrefix(msg, "table or view '") {
if strings.Contains(msg, "not found") {
return ErrTableNotFound
}
if strings.Contains(msg, "already exists") {
return ErrTableExists
}
}
return ErrGeneral
}
const inlineColTypesCap = 8
// Version returns the stoolap engine version.
func Version() (string, error) {
if err := loadLibrary(); err != nil {
return "", err
}
return goString(unsafe.Pointer(abiCall1(sym.version, 0))), nil
}
// DB represents a stoolap database connection.
type DB struct {
ptr uintptr
}
// errStr reads the error message from a handle (db, tx, stmt, or 0 for global).
func errStr(fn, handle uintptr) string {
return goString(unsafe.Pointer(abiCall1(fn, handle)))
}
// Open opens a database with the given DSN.
func Open(dsn string) (*DB, error) {
if err := loadLibrary(); err != nil {
return nil, err
}
cs := newCStr(dsn)
var dbPtr uintptr
rc := abiCall2(sym.open, cs.ptr, uintptr(unsafe.Pointer(&dbPtr)))
cs.keepAlive()
if int32(rc) != stoolapOK {
return nil, newError(errStr(sym.errmsg, 0))
}
return &DB{ptr: dbPtr}, nil
}
// OpenMemory opens a new in-memory database.
func OpenMemory() (*DB, error) {
if err := loadLibrary(); err != nil {
return nil, err
}
var dbPtr uintptr
rc := abiCall1(sym.openInMemory, uintptr(unsafe.Pointer(&dbPtr)))
if int32(rc) != stoolapOK {
return nil, newError(errStr(sym.errmsg, 0))
}
return &DB{ptr: dbPtr}, nil
}
// Close closes the database.
func (db *DB) Close() error {
if db.ptr == 0 {
return nil
}
abiCall1(sym.close, db.ptr)
db.ptr = 0
return nil
}
// Clone creates a cloned handle for concurrent use.
func (db *DB) Clone() (*DB, error) {
if db.ptr == 0 {
return nil, errDBClosed
}
var clonePtr uintptr
rc := abiCall2(sym.clone, db.ptr, uintptr(unsafe.Pointer(&clonePtr)))
if int32(rc) != stoolapOK {
return nil, newError(errStr(sym.errmsg, db.ptr))
}
return &DB{ptr: clonePtr}, nil
}
// Exec executes a SQL statement.
func (db *DB) Exec(ctx context.Context, query string) (sql.Result, error) {
if db.ptr == 0 {
return nil, errDBClosed
}
if err := ctx.Err(); err != nil {
return nil, err
}
cs := newCStr(query)
var affected int64
rc := abiCall3(sym.exec, db.ptr, cs.ptr, uintptr(unsafe.Pointer(&affected)))
cs.keepAlive()
if int32(rc) != stoolapOK {
return nil, newError(errStr(sym.errmsg, db.ptr))
}
return execResult(affected), nil
}
// ExecParams executes a SQL statement with positional parameters.
func (db *DB) ExecParams(ctx context.Context, query string, args []any) (sql.Result, error) {
if db.ptr == 0 {
return nil, errDBClosed
}
if err := ctx.Err(); err != nil {
return nil, err
}
if len(args) == 0 {
return db.Exec(ctx, query)
}
cs := newCStr(query)
ep, err := encodeParams(args)
if err != nil {
return nil, err
}
var affected int64
rc := abiCall5(sym.execParams, db.ptr, cs.ptr, ep.ptr, uintptr(int32(len(args))), uintptr(unsafe.Pointer(&affected)))
cs.keepAlive()
ep.keepAlive()
if int32(rc) != stoolapOK {
return nil, newError(errStr(sym.errmsg, db.ptr))
}
return execResult(affected), nil
}
// Query executes a query that returns rows.
func (db *DB) Query(ctx context.Context, query string) (*Rows, error) {
if db.ptr == 0 {
return nil, errDBClosed
}
if err := ctx.Err(); err != nil {
return nil, err
}
cs := newCStr(query)
var rowsPtr uintptr
rc := abiCall3(sym.query, db.ptr, cs.ptr, uintptr(unsafe.Pointer(&rowsPtr)))
cs.keepAlive()
if int32(rc) != stoolapOK {
return nil, newError(errStr(sym.errmsg, db.ptr))
}
return newRows(rowsPtr), nil
}
// QueryParams executes a query with positional parameters.
func (db *DB) QueryParams(ctx context.Context, query string, args []any) (*Rows, error) {
if db.ptr == 0 {
return nil, errDBClosed
}
if err := ctx.Err(); err != nil {
return nil, err
}
if len(args) == 0 {
return db.Query(ctx, query)
}
cs := newCStr(query)
ep, err := encodeParams(args)
if err != nil {
return nil, err
}
var rowsPtr uintptr
rc := abiCall5(sym.queryParams, db.ptr, cs.ptr, ep.ptr, uintptr(int32(len(args))), uintptr(unsafe.Pointer(&rowsPtr)))
cs.keepAlive()
ep.keepAlive()
if int32(rc) != stoolapOK {
return nil, newError(errStr(sym.errmsg, db.ptr))
}
return newRows(rowsPtr), nil
}
// Prepare creates a prepared statement.
func (db *DB) Prepare(ctx context.Context, query string) (*Stmt, error) {
if db.ptr == 0 {
return nil, errDBClosed
}
if err := ctx.Err(); err != nil {
return nil, err
}
cs := newCStr(query)
var stmtPtr uintptr
rc := abiCall3(sym.prepare, db.ptr, cs.ptr, uintptr(unsafe.Pointer(&stmtPtr)))
cs.keepAlive()
if int32(rc) != stoolapOK {
return nil, newError(errStr(sym.errmsg, db.ptr))
}
return &Stmt{ptr: stmtPtr}, nil
}
// Begin starts a transaction.
func (db *DB) Begin(ctx context.Context) (*Tx, error) {
if db.ptr == 0 {
return nil, errDBClosed
}
if err := ctx.Err(); err != nil {
return nil, err
}
var txPtr uintptr
rc := abiCall2(sym.begin, db.ptr, uintptr(unsafe.Pointer(&txPtr)))
if int32(rc) != stoolapOK {
return nil, newError(errStr(sym.errmsg, db.ptr))
}
return &Tx{ptr: txPtr}, nil
}
// BeginTx starts a transaction with options.
func (db *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
if db.ptr == 0 {
return nil, errDBClosed
}
if err := ctx.Err(); err != nil {
return nil, err
}
isolation := int32(isolationReadCommitted)
if opts != nil {
switch sql.IsolationLevel(opts.Isolation) {
case sql.LevelDefault, sql.LevelReadCommitted:
case sql.LevelSnapshot, sql.LevelRepeatableRead:
isolation = isolationSnapshot
default:
return nil, errors.New("stoolap: unsupported isolation level")
}
}
var txPtr uintptr
rc := abiCall3(sym.beginIso, db.ptr, uintptr(isolation), uintptr(unsafe.Pointer(&txPtr)))
if int32(rc) != stoolapOK {
return nil, newError(errStr(sym.errmsg, db.ptr))
}
return &Tx{ptr: txPtr}, nil
}
// ─── Rows ───────────────────────────────────────────────────────────────────
// Rows is an iterator over query results.
type Rows struct {
ptr uintptr
cols []string
colTypes []int32
colCount int
closed bool
colTypesLoaded bool
colTypesInline [inlineColTypesCap]int32
textBuf []byte // reusable buffer for batching text copies in Scan
colNameBuf []byte // reusable scratch for gathering column names in Columns
}
var rowsPool = sync.Pool{New: func() any { return &Rows{} }}
func newRows(ptr uintptr) *Rows {
r := rowsPool.Get().(*Rows)
r.reset(ptr)
return r
}
// Columns returns the column names as a Go-owned slice, safe to hold after Close().
// First call per query: 2 allocations (one string for combined name data, one []string).
// Subsequent calls on the same Rows return the cached slice with no allocation.
func (r *Rows) Columns() []string {
if r.cols != nil {
return r.cols
}
// Inline scratch for per-column end offsets; fits the vast majority of tables.
var inlineEnds [32]int
var ends []int
if r.colCount <= len(inlineEnds) {
ends = inlineEnds[:r.colCount]
} else {
ends = make([]int, r.colCount)
}
// Pass 1: gather all column-name bytes into a reusable scratch buffer,
// recording where each name ends.
buf := r.colNameBuf[:0]
for i := 0; i < r.colCount; i++ {
p := unsafe.Pointer(abiCall2(sym.rowsColName, r.ptr, uintptr(i)))
if p != nil {
n := 0
for *(*byte)(unsafe.Add(p, n)) != 0 {
n++
}
if n > 0 {
buf = append(buf, unsafe.Slice((*byte)(p), n)...)
}
}
ends[i] = len(buf)
}
r.colNameBuf = buf
// One Go-owned allocation holding all the bytes.
all := string(buf)
cols := make([]string, r.colCount)
prev := 0
for i := 0; i < r.colCount; i++ {
cols[i] = all[prev:ends[i]]
prev = ends[i]
}
r.cols = cols
return cols
}
// IsNull reports whether the current row has a NULL value at column i.
func (r *Rows) IsNull(i int) bool {
return int32(abiCall2(sym.rowsColIsNull, r.ptr, uintptr(i))) == 1
}
// Int64 returns the current row's INTEGER value at column i.
func (r *Rows) Int64(i int) int64 {
return int64(abiCall2(sym.rowsColInt64, r.ptr, uintptr(i)))
}
// Float64 returns the current row's FLOAT value at column i.
func (r *Rows) Float64(i int) float64 {
return abiCallFloat2(sym.rowsColDouble, r.ptr, uintptr(i))
}
// Bool returns the current row's BOOLEAN value at column i.
func (r *Rows) Bool(i int) bool {
return int32(abiCall2(sym.rowsColBool, r.ptr, uintptr(i))) != 0
}
// Timestamp returns the current row's TIMESTAMP value at column i.
func (r *Rows) Timestamp(i int) time.Time {
nanos := int64(abiCall2(sym.rowsColTimestamp, r.ptr, uintptr(i)))
return time.Unix(nanos/1e9, nanos%1e9).UTC()
}
// Next advances to the next row.
func (r *Rows) Next() bool {
if r.closed {
return false
}
if int32(abiCall1(sym.rowsNext, r.ptr)) != stoolapRow {
return false
}
return true
}
// Scan reads the current row into dest.
// Text columns are batched into a single string allocation per row.
// The textBuf is reused across rows via Rows pooling.
func (r *Rows) Scan(dest ...any) error {
if r.closed {
return errRowsClosed
}
if len(dest) != r.colCount {
return errColumnCount
}
rp := r.ptr
r.textBuf = r.textBuf[:0]
const maxTextRefs = 16
type tref struct {
destIdx int
start int
len int
}
var refs [maxTextRefs]tref
nRefs := 0
appendText := func(v uintptr, n int64, destIdx int) bool {
if nRefs >= maxTextRefs {
return false
}
start := len(r.textBuf)
size := int(n)
r.textBuf = append(r.textBuf, unsafe.Slice((*byte)(unsafe.Pointer(v)), size)...)
refs[nRefs] = tref{destIdx: destIdx, start: start, len: size}
nRefs++
return true
}
for i, d := range dest {
idx := uintptr(i)
isNull := int32(abiCall2(sym.rowsColIsNull, rp, idx)) == 1
switch p := d.(type) {
case *int64:
if isNull {
*p = 0
} else {
*p = r.Int64(i)
}
case *float64:
if isNull {
*p = 0
} else {
*p = r.Float64(i)
}
case *string:
if isNull {
*p = ""
} else {
v, n := abiCallPtrLen(sym.rowsColText, rp, idx)
if v == 0 || n <= 0 {
*p = ""
} else if !appendText(v, n, i) {
*p = goStringN(unsafe.Pointer(v), int(n))
}
}
case *bool:
if isNull {
*p = false
} else {
*p = r.Bool(i)
}
case *time.Time:
if isNull {
*p = time.Time{}
} else {
*p = r.Timestamp(i)
}
case *[]byte:
if isNull {
*p = nil
} else {
*p = r.readColBlob(i)
}
case *sql.NullString:
if isNull {
p.String = ""
p.Valid = false
} else {
v, n := abiCallPtrLen(sym.rowsColText, rp, idx)
if v == 0 {
p.String = ""
p.Valid = false
} else if !appendText(v, n, i) {
p.String = goStringN(unsafe.Pointer(v), int(n))
p.Valid = true
}
}
case *sql.NullInt64:
if isNull {
p.Int64 = 0
p.Valid = false
} else {
p.Int64 = int64(abiCall2(sym.rowsColInt64, rp, idx))
p.Valid = true
}
case *sql.NullFloat64:
if isNull {
p.Float64 = 0
p.Valid = false
} else {
p.Float64 = r.Float64(i)
p.Valid = true
}
case *sql.NullBool:
if isNull {
p.Bool = false
p.Valid = false
} else {
p.Bool = r.Bool(i)
p.Valid = true
}
case *sql.NullTime:
if isNull {
p.Time = time.Time{}
p.Valid = false
} else {
p.Time = r.Timestamp(i)
p.Valid = true
}
case *any:
if isNull {
*p = nil
} else {
r.ensureColTypes()
switch r.colTypes[i] {
case typeInteger:
*p = r.Int64(i)
case typeFloat:
*p = r.Float64(i)
case typeText, typeJSON:
v, n := abiCallPtrLen(sym.rowsColText, rp, idx)
if !appendText(v, n, i) {
*p = goStringN(unsafe.Pointer(v), int(n))
}
case typeBoolean:
*p = r.Bool(i)
case typeTimestamp:
*p = r.Timestamp(i)
case typeBlob:
*p = r.readColBlob(i)
default:
*p = nil
}
}
default:
return errUnsupportedDest
}
}
// Batch-create all text strings from one allocation.
// string(r.textBuf) copies once; substrings share the backing array.
if nRefs > 0 {
all := string(r.textBuf)
for j := range nRefs {
ref := refs[j]
s := all[ref.start : ref.start+ref.len]
switch p := dest[ref.destIdx].(type) {
case *string:
*p = s
case *sql.NullString:
p.String = s
p.Valid = true
case *any:
*p = s
}
}
}
return nil
}
// FetchAll fetches all remaining rows in a single native call and returns them
// as a slice of []any rows. Dramatically faster for large result sets.
// After calling FetchAll, the Rows handle is consumed; call Close() afterward.
func (r *Rows) FetchAll() ([][]any, error) {
if r.closed {
return nil, errRowsClosed
}
var bufPtr uintptr
var bufLen int64
rc := abiCall3(sym.rowsFetchAll, r.ptr, uintptr(unsafe.Pointer(&bufPtr)), uintptr(unsafe.Pointer(&bufLen)))
if int32(rc) != stoolapOK {
return nil, errors.New("stoolap: fetch_all failed")
}
if bufPtr == 0 || bufLen == 0 {
return nil, nil
}
// Copy the buffer from C into Go, then free the C buffer
buf := copyBlob(unsafe.Pointer(bufPtr), bufLen)
abiCall2(sym.bufferFree, bufPtr, uintptr(bufLen))
return parseFetchAllBuffer(buf)
}
// Close closes the result set.
func (r *Rows) Close() error {
if r.closed {
return nil
}
r.closed = true
abiCallVoid1(sym.rowsClose, r.ptr)
r.ptr = 0
// Release the columns slice so the next pooled use cannot share its
// backing array with a caller that is still holding a previous result.
// textBuf / colNameBuf stay — they hold no externally-visible data.
r.cols = nil
rowsPool.Put(r)
return nil
}
// ─── Stmt ───────────────────────────────────────────────────────────────────
// Stmt is a prepared statement.
type Stmt struct {
mu sync.Mutex
ptr uintptr
scratch stmtParamScratch
}
// ExecContext executes a prepared statement with parameters.
func (s *Stmt) ExecContext(ctx context.Context, args []any) (sql.Result, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
s.mu.Lock()
defer s.mu.Unlock()
if s.ptr == 0 {
return nil, errStmtClosed
}
ep, err := s.scratch.encode(args)
if err != nil {
return nil, err
}
var affected int64
rc := abiCall4(sym.stmtExec, s.ptr, ep.ptr, uintptr(int32(len(args))), uintptr(unsafe.Pointer(&affected)))
ep.keepAlive()
if int32(rc) != stoolapOK {
return nil, newError(errStr(sym.stmtErrmsg, s.ptr))
}
return execResult(affected), nil
}
// QueryContext executes a prepared statement query with parameters.
func (s *Stmt) QueryContext(ctx context.Context, args []any) (*Rows, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
s.mu.Lock()
defer s.mu.Unlock()
if s.ptr == 0 {
return nil, errStmtClosed
}
ep, err := s.scratch.encode(args)
if err != nil {
return nil, err
}
var rowsPtr uintptr
rc := abiCall4(sym.stmtQuery, s.ptr, ep.ptr, uintptr(int32(len(args))), uintptr(unsafe.Pointer(&rowsPtr)))
ep.keepAlive()
if int32(rc) != stoolapOK {
return nil, newError(errStr(sym.stmtErrmsg, s.ptr))
}
return newRows(rowsPtr), nil
}
// Close destroys the prepared statement.
func (s *Stmt) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.ptr == 0 {
return nil
}
abiCallVoid1(sym.stmtFinalize, s.ptr)
s.ptr = 0
s.scratch.reset()
return nil
}
// ─── Tx ─────────────────────────────────────────────────────────────────────
// Tx is a database transaction.
type Tx struct {
ptr uintptr
}
// Exec executes within the transaction.
func (tx *Tx) Exec(ctx context.Context, query string) (sql.Result, error) {
if tx.ptr == 0 {
return nil, errTxDone
}
if err := ctx.Err(); err != nil {
return nil, err
}
cs := newCStr(query)
var affected int64
rc := abiCall3(sym.txExec, tx.ptr, cs.ptr, uintptr(unsafe.Pointer(&affected)))
cs.keepAlive()
if int32(rc) != stoolapOK {
return nil, newError(errStr(sym.txErrmsg, tx.ptr))
}
return execResult(affected), nil
}
// ExecParams executes with parameters within the transaction.
func (tx *Tx) ExecParams(ctx context.Context, query string, args []any) (sql.Result, error) {
if tx.ptr == 0 {
return nil, errTxDone
}
if err := ctx.Err(); err != nil {
return nil, err
}
if len(args) == 0 {
return tx.Exec(ctx, query)
}
cs := newCStr(query)
ep, err := encodeParams(args)
if err != nil {
return nil, err
}
var affected int64
rc := abiCall5(sym.txExecParams, tx.ptr, cs.ptr, ep.ptr, uintptr(int32(len(args))), uintptr(unsafe.Pointer(&affected)))
cs.keepAlive()
ep.keepAlive()
if int32(rc) != stoolapOK {
return nil, newError(errStr(sym.txErrmsg, tx.ptr))
}
return execResult(affected), nil
}
// Query within the transaction.
func (tx *Tx) Query(ctx context.Context, query string) (*Rows, error) {
if tx.ptr == 0 {
return nil, errTxDone
}
if err := ctx.Err(); err != nil {
return nil, err
}
cs := newCStr(query)
var rowsPtr uintptr
rc := abiCall3(sym.txQuery, tx.ptr, cs.ptr, uintptr(unsafe.Pointer(&rowsPtr)))
cs.keepAlive()
if int32(rc) != stoolapOK {
return nil, newError(errStr(sym.txErrmsg, tx.ptr))
}
return newRows(rowsPtr), nil
}
// QueryParams executes a query with parameters within the transaction.
func (tx *Tx) QueryParams(ctx context.Context, query string, args []any) (*Rows, error) {
if tx.ptr == 0 {
return nil, errTxDone
}
if err := ctx.Err(); err != nil {
return nil, err
}
if len(args) == 0 {
return tx.Query(ctx, query)
}
cs := newCStr(query)
ep, err := encodeParams(args)
if err != nil {
return nil, err
}
var rowsPtr uintptr
rc := abiCall5(sym.txQueryParams, tx.ptr, cs.ptr, ep.ptr, uintptr(int32(len(args))), uintptr(unsafe.Pointer(&rowsPtr)))
cs.keepAlive()
ep.keepAlive()
if int32(rc) != stoolapOK {
return nil, newError(errStr(sym.txErrmsg, tx.ptr))
}
return newRows(rowsPtr), nil
}
// Commit commits the transaction.
// The underlying transaction handle is freed whether commit succeeds or fails,
// so tx.ptr is always zeroed. On failure the error is retrieved from the
// process-global error slot (the handle is no longer valid).
func (tx *Tx) Commit() error {
if tx.ptr == 0 {
return nil
}
rc := abiCall1(sym.txCommit, tx.ptr)
tx.ptr = 0
if int32(rc) != stoolapOK {
return newError(errStr(sym.errmsg, 0))
}
return nil
}
// Rollback rolls back the transaction.
func (tx *Tx) Rollback() error {
if tx.ptr == 0 {
return nil
}
abiCallVoid1(sym.txRollback, tx.ptr)
tx.ptr = 0
return nil
}
// ─── Parameter encoding ─────────────────────────────────────────────────────
// StoolapValue C layout (64-bit native):
//
// [0:4] int32 value_type
// [4:8] int32 _padding
// [8:24] union (16 bytes)
// int64/float64/timestamp: 8 bytes at offset 8
// bool: int32 at offset 8
// text/blob: pointer(8 bytes) at offset 8 + length(8 bytes) at offset 16
const stoolapValueSize = 24
const maxPooledParamBufCap = stoolapValueSize * 64
const maxPooledParamDataCap = 16 << 10
var encodedParamsBufPool = sync.Pool{
New: func() any {
b := make([]byte, 0, stoolapValueSize*8)
return &b
},
}
var encodedParamsDataPool = sync.Pool{
New: func() any {
b := make([]byte, 0, 256)
return &b
},
}
// encodedParams holds the encoded StoolapValue array and keeps all
// Go-allocated buffers alive until the FFI call completes.
type encodedParams struct {
ptr uintptr // pointer to buf[0]
buf []byte // StoolapValue array
data []byte // packed string/blob data
bufpb *[]byte
datapb *[]byte
}
type stmtParamScratch struct {
buf []byte
data []byte
}
func (ep *encodedParams) keepAlive() {
runtime.KeepAlive(ep.buf)
runtime.KeepAlive(ep.data)
if ep.bufpb != nil {
*ep.bufpb = ep.buf[:0]
encodedParamsBufPool.Put(ep.bufpb)
}
if ep.datapb != nil {
*ep.datapb = ep.data[:0]
encodedParamsDataPool.Put(ep.datapb)
}
}
func (ps *stmtParamScratch) encode(args []any) (encodedParams, error) {
if len(args) == 0 {
return encodedParams{}, nil
}
ps.buf = resizeAndClearBytes(ps.buf, len(args)*stoolapValueSize)
ps.data = resizeBytes(ps.data, paramsDataSize(args))
return encodeParamsBuffers(args, ps.buf, ps.data)
}
func (ps *stmtParamScratch) reset() {
ps.buf = nil
ps.data = nil
}
func encodeParams(args []any) (encodedParams, error) {
if len(args) == 0 {
return encodedParams{}, nil
}
size := len(args) * stoolapValueSize
var buf []byte
var bufpb *[]byte
if size <= maxPooledParamBufCap {
bufpb = encodedParamsBufPool.Get().(*[]byte)
buf = *bufpb
buf = resizeAndClearBytes(buf, size)
*bufpb = buf
} else {
buf = resizeAndClearBytes(nil, size)
}
dataSize := paramsDataSize(args)
var data []byte
var datapb *[]byte
if dataSize > 0 {
if dataSize <= maxPooledParamDataCap {
datapb = encodedParamsDataPool.Get().(*[]byte)
data = *datapb
data = resizeBytes(data, dataSize)
*datapb = data
} else {
data = resizeBytes(nil, dataSize)
}
}
ep, err := encodeParamsBuffers(args, buf, data)
if err != nil {
if bufpb != nil {
encodedParamsBufPool.Put(bufpb)
}
if datapb != nil {
encodedParamsDataPool.Put(datapb)
}
return encodedParams{}, err
}
ep.bufpb = bufpb
ep.datapb = datapb
return ep, nil
}
// putPtr writes a native pointer value into a byte slice.
func putPtr(b []byte, p uintptr) {
switch unsafe.Sizeof(uintptr(0)) {
case 8:
binary.LittleEndian.PutUint64(b, uint64(p))
case 4:
binary.LittleEndian.PutUint32(b, uint32(p))
}
}
func paramsDataSize(args []any) int {
dataSize := 0
for _, arg := range args {
switch v := arg.(type) {
case string:
dataSize += len(v)
case []byte:
dataSize += len(v)
}
}
return dataSize
}
func resizeAndClearBytes(buf []byte, size int) []byte {
if size == 0 {
return buf[:0]
}
if cap(buf) < size {
return make([]byte, size)
}
buf = buf[:size]
clear(buf)
return buf
}
func resizeBytes(buf []byte, size int) []byte {
if size == 0 {
return buf[:0]