forked from marcboeker/go-duckdb
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathstatement.go
More file actions
722 lines (633 loc) · 22.6 KB
/
statement.go
File metadata and controls
722 lines (633 loc) · 22.6 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
package duckdb
import (
"context"
"database/sql/driver"
"errors"
"fmt"
"math/big"
"reflect"
"github.com/duckdb/duckdb-go/v2/mapping"
)
type StmtType mapping.StatementType
const (
STATEMENT_TYPE_INVALID = StmtType(mapping.StatementTypeInvalid)
STATEMENT_TYPE_SELECT = StmtType(mapping.StatementTypeSelect)
STATEMENT_TYPE_INSERT = StmtType(mapping.StatementTypeInsert)
STATEMENT_TYPE_UPDATE = StmtType(mapping.StatementTypeUpdate)
STATEMENT_TYPE_EXPLAIN = StmtType(mapping.StatementTypeExplain)
STATEMENT_TYPE_DELETE = StmtType(mapping.StatementTypeDelete)
STATEMENT_TYPE_PREPARE = StmtType(mapping.StatementTypePrepare)
STATEMENT_TYPE_CREATE = StmtType(mapping.StatementTypeCreate)
STATEMENT_TYPE_EXECUTE = StmtType(mapping.StatementTypeExecute)
STATEMENT_TYPE_ALTER = StmtType(mapping.StatementTypeAlter)
STATEMENT_TYPE_TRANSACTION = StmtType(mapping.StatementTypeTransaction)
STATEMENT_TYPE_COPY = StmtType(mapping.StatementTypeCopy)
STATEMENT_TYPE_ANALYZE = StmtType(mapping.StatementTypeAnalyze)
STATEMENT_TYPE_VARIABLE_SET = StmtType(mapping.StatementTypeVariableSet)
STATEMENT_TYPE_CREATE_FUNC = StmtType(mapping.StatementTypeCreateFunc)
STATEMENT_TYPE_DROP = StmtType(mapping.StatementTypeDrop)
STATEMENT_TYPE_EXPORT = StmtType(mapping.StatementTypeExport)
STATEMENT_TYPE_PRAGMA = StmtType(mapping.StatementTypePragma)
STATEMENT_TYPE_VACUUM = StmtType(mapping.StatementTypeVacuum)
STATEMENT_TYPE_CALL = StmtType(mapping.StatementTypeCall)
STATEMENT_TYPE_SET = StmtType(mapping.StatementTypeSet)
STATEMENT_TYPE_LOAD = StmtType(mapping.StatementTypeLoad)
STATEMENT_TYPE_RELATION = StmtType(mapping.StatementTypeRelation)
STATEMENT_TYPE_EXTENSION = StmtType(mapping.StatementTypeExtension)
STATEMENT_TYPE_LOGICAL_PLAN = StmtType(mapping.StatementTypeLogicalPlan)
STATEMENT_TYPE_ATTACH = StmtType(mapping.StatementTypeAttach)
STATEMENT_TYPE_DETACH = StmtType(mapping.StatementTypeDetach)
STATEMENT_TYPE_MULTI = StmtType(mapping.StatementTypeMulti)
)
// Stmt implements the driver.Stmt interface.
type Stmt struct {
conn *Conn
preparedStmt *mapping.PreparedStatement
closeOnRowsClose bool
bound bool
closed bool
rows bool
}
// checkState checks if the statement is closed or uninitialized.
func (s *Stmt) checkState() error {
if s.closed {
return errClosedStmt
}
if s.preparedStmt == nil {
return errUninitializedStmt
}
return nil
}
// Close the statement.
// Implements the driver.Stmt interface.
func (s *Stmt) Close() error {
if s.rows {
panic("database/sql/driver: misuse of duckdb driver: Close with active Rows")
}
if s.closed {
panic("database/sql/driver: misuse of duckdb driver: double Close of Stmt")
}
s.closed = true
mapping.DestroyPrepare(s.preparedStmt)
return nil
}
// NumInput returns the number of placeholder parameters.
// Implements the driver.Stmt interface.
func (s *Stmt) NumInput() int {
if s.closed {
panic("database/sql/driver: misuse of duckdb driver: NumInput after Close")
}
count := mapping.NParams(*s.preparedStmt)
return int(count)
}
// ParamName returns the name of the parameter at the given index (1-based).
func (s *Stmt) ParamName(n int) (string, error) {
if err := s.checkState(); err != nil {
return "", err
}
count := mapping.NParams(*s.preparedStmt)
if n == 0 || n > int(count) {
return "", getError(errAPI, paramIndexError(n, uint64(count)))
}
name := mapping.ParameterName(*s.preparedStmt, mapping.IdxT(n))
return name, nil
}
// ParamType returns the expected type of the parameter at the given index (1-based).
func (s *Stmt) ParamType(n int) (Type, error) {
if err := s.checkState(); err != nil {
return TYPE_INVALID, err
}
count := mapping.NParams(*s.preparedStmt)
if n == 0 || n > int(count) {
return TYPE_INVALID, getError(errAPI, paramIndexError(n, uint64(count)))
}
t := mapping.ParamType(*s.preparedStmt, mapping.IdxT(n))
return t, nil
}
func (s *Stmt) paramLogicalType(n int) (mapping.LogicalType, error) {
var lt mapping.LogicalType
if err := s.checkState(); err != nil {
return lt, err
}
count := mapping.NParams(*s.preparedStmt)
if n == 0 || n > int(count) {
return lt, getError(errAPI, paramIndexError(n, uint64(count)))
}
return mapping.ParamLogicalType(*s.preparedStmt, mapping.IdxT(n)), nil
}
// StatementType returns the type of the statement.
func (s *Stmt) StatementType() (StmtType, error) {
if err := s.checkState(); err != nil {
return STATEMENT_TYPE_INVALID, err
}
t := mapping.PreparedStatementType(*s.preparedStmt)
return StmtType(t), nil
}
// Bind the parameters to the statement.
// WARNING: This is a low-level API and should be used with caution.
func (s *Stmt) Bind(args []driver.NamedValue) error {
return s.BindWithCtx(context.Background(), args)
}
// BindWithCtx takes a context and binds the parameters to the statement.
// WARNING: This is a low-level API and should be used with caution.
func (s *Stmt) BindWithCtx(ctx context.Context, args []driver.NamedValue) error {
if err := ctx.Err(); err != nil {
return err
}
if s.closed {
return errors.Join(errCouldNotBind, errClosedStmt)
}
if s.preparedStmt == nil {
return errors.Join(errCouldNotBind, errUninitializedStmt)
}
return s.bind(args)
}
func (s *Stmt) bindHugeint(val *big.Int, n int) (mapping.State, error) {
hugeint, err := hugeIntFromNative(val)
if err != nil {
return mapping.StateError, err
}
state := mapping.BindHugeInt(*s.preparedStmt, mapping.IdxT(n+1), hugeint)
return state, nil
}
func (s *Stmt) bindUhugeint(val *big.Int, n int) (mapping.State, error) {
uhugeint, err := uhugeIntFromNative(val)
if err != nil {
return mapping.StateError, err
}
state := mapping.BindUHugeInt(*s.preparedStmt, mapping.IdxT(n+1), uhugeint)
return state, nil
}
func (s *Stmt) bindBigNum(val *big.Int, n int) (mapping.State, error) {
bignum := bigNumFromNative(val)
defer mapping.DestroyBigNum(&bignum)
v := mapping.CreateBigNum(bignum)
defer mapping.DestroyValue(&v)
state := mapping.BindValue(*s.preparedStmt, mapping.IdxT(n+1), v)
return state, nil
}
func (s *Stmt) bindTimestamp(val driver.NamedValue, t Type, n int) (mapping.State, error) {
var state mapping.State
switch t {
case TYPE_TIMESTAMP:
v, err := inferTimestamp(t, val.Value)
if err != nil {
return mapping.StateError, err
}
state = mapping.BindTimestamp(*s.preparedStmt, mapping.IdxT(n+1), v)
case TYPE_TIMESTAMP_TZ:
v, err := inferTimestamp(t, val.Value)
if err != nil {
return mapping.StateError, err
}
state = mapping.BindTimestampTZ(*s.preparedStmt, mapping.IdxT(n+1), v)
case TYPE_TIMESTAMP_S:
v, err := inferTimestampS(val.Value)
if err != nil {
return mapping.StateError, err
}
tS := mapping.CreateTimestampS(v)
state = mapping.BindValue(*s.preparedStmt, mapping.IdxT(n+1), tS)
mapping.DestroyValue(&tS)
case TYPE_TIMESTAMP_MS:
v, err := inferTimestampMS(val.Value)
if err != nil {
return mapping.StateError, err
}
tMS := mapping.CreateTimestampMS(v)
state = mapping.BindValue(*s.preparedStmt, mapping.IdxT(n+1), tMS)
mapping.DestroyValue(&tMS)
case TYPE_TIMESTAMP_NS:
v, err := inferTimestampNS(val.Value)
if err != nil {
return mapping.StateError, err
}
tMS := mapping.CreateTimestampNS(v)
state = mapping.BindValue(*s.preparedStmt, mapping.IdxT(n+1), tMS)
mapping.DestroyValue(&tMS)
}
return state, nil
}
func (s *Stmt) bindDate(val driver.NamedValue, n int) (mapping.State, error) {
date, err := inferDate(val.Value)
if err != nil {
return mapping.StateError, err
}
state := mapping.BindDate(*s.preparedStmt, mapping.IdxT(n+1), date)
return state, nil
}
func (s *Stmt) bindTime(val driver.NamedValue, t Type, n int) (mapping.State, error) {
ticks, err := getTimeTicks(val.Value)
if err != nil {
return mapping.StateError, err
}
if t == TYPE_TIME {
ti := mapping.NewTime(ticks)
state := mapping.BindTime(*s.preparedStmt, mapping.IdxT(n+1), ti)
return state, nil
}
// TYPE_TIME_TZ: Preserve the UTC offset from the input time.
goTime, _ := castToTime(val.Value)
_, offset := goTime.Zone()
ti := mapping.CreateTimeTZ(ticks, int32(offset))
v := mapping.CreateTimeTZValue(ti)
state := mapping.BindValue(*s.preparedStmt, mapping.IdxT(n+1), v)
mapping.DestroyValue(&v)
return state, nil
}
func (s *Stmt) bindJSON(val driver.NamedValue, n int) (mapping.State, error) {
switch v := val.Value.(type) {
case []byte:
return mapping.BindVarcharLength(*s.preparedStmt, mapping.IdxT(n+1), string(v), mapping.IdxT(len(v))), nil
case string:
return mapping.BindVarcharLength(*s.preparedStmt, mapping.IdxT(n+1), v, mapping.IdxT(len(v))), nil
case nil:
return mapping.BindNull(*s.preparedStmt, mapping.IdxT(n+1)), nil
}
return mapping.StateError, addIndexToError(unsupportedTypeError("JSON interface, need []byte, string or nil"), n+1)
}
func (s *Stmt) bindUUID(val driver.NamedValue, n int) (mapping.State, error) {
// Check if the interface contains a nil pointer using reflection
v := reflect.ValueOf(val.Value)
if v.Kind() == reflect.Ptr && v.IsNil() {
return mapping.BindNull(*s.preparedStmt, mapping.IdxT(n+1)), nil
}
if ss, ok := val.Value.(fmt.Stringer); ok {
str := ss.String()
return mapping.BindVarcharLength(*s.preparedStmt, mapping.IdxT(n+1), str, mapping.IdxT(len(str))), nil
}
return mapping.StateError, addIndexToError(unsupportedTypeError(unknownTypeErrMsg), n+1)
}
// Used for binding Array, List, Struct, Map. In the future, Union.
func (s *Stmt) bindCompositeValue(val driver.NamedValue, n int) (mapping.State, error) {
lt, err := s.paramLogicalType(n + 1)
defer mapping.DestroyLogicalType(<)
if err != nil {
return mapping.StateError, err
}
mappedVal, err := createValue(lt, val.Value)
defer mapping.DestroyValue(&mappedVal)
if err != nil {
return mapping.StateError, addIndexToError(err, n+1)
}
state := mapping.BindValue(*s.preparedStmt, mapping.IdxT(n+1), mappedVal)
return state, nil
}
func (s *Stmt) tryBindComplexValue(val driver.NamedValue, n int) (mapping.State, error) {
lt, mappedVal, err := inferLogicalTypeAndValue(val.Value)
defer mapping.DestroyLogicalType(<)
defer mapping.DestroyValue(&mappedVal)
if err != nil {
return mapping.StateError, addIndexToError(err, n+1)
}
state := mapping.BindValue(*s.preparedStmt, mapping.IdxT(n+1), mappedVal)
return state, nil
}
func (s *Stmt) bindComplexValue(val driver.NamedValue, n int, t Type, name string) (mapping.State, error) {
// We could not resolve this parameter when binding the query.
// Fall back to the Go type.
if t == TYPE_INVALID {
return s.tryBindComplexValue(val, n)
}
switch t {
case TYPE_UUID:
return s.bindUUID(val, n)
case TYPE_TIMESTAMP, TYPE_TIMESTAMP_TZ, TYPE_TIMESTAMP_S, TYPE_TIMESTAMP_MS, TYPE_TIMESTAMP_NS:
return s.bindTimestamp(val, t, n)
case TYPE_DATE:
return s.bindDate(val, n)
case TYPE_TIME, TYPE_TIME_TZ:
return s.bindTime(val, t, n)
case TYPE_ARRAY, TYPE_LIST, TYPE_STRUCT, TYPE_MAP:
return s.bindCompositeValue(val, n)
case TYPE_ENUM, TYPE_UNION:
// FIXME: for other types: duckdb_param_logical_type once available, then create duckdb_value + duckdb_bind_value
// FIXME: for other types: use NamedValueChecker to support.
return mapping.StateError, addIndexToError(unsupportedTypeError(name), n+1)
}
return mapping.StateError, addIndexToError(unsupportedTypeError(unknownTypeErrMsg), n+1)
}
//nolint:gocyclo
func (s *Stmt) bindValue(val driver.NamedValue, n int) (mapping.State, error) {
// For some queries, we cannot resolve the parameter type when preparing the query.
// E.g., for "SELECT * FROM (VALUES (?, ?)) t(a, b)", we cannot know the parameter types from the SQL statement alone.
// For these cases, ParamType returns TYPE_INVALID.
t, err := s.ParamType(n + 1)
if err != nil {
return mapping.StateError, err
}
name, ok := unsupportedTypeToStringMap[t]
if ok && t != TYPE_INVALID {
return mapping.StateError, addIndexToError(unsupportedTypeError(name), n+1)
}
if t != TYPE_INVALID {
lt, e := s.paramLogicalType(n + 1)
defer mapping.DestroyLogicalType(<)
if e != nil {
return mapping.StateError, e
}
alias := mapping.LogicalTypeGetAlias(lt)
if alias == aliasJSON {
return s.bindJSON(val, n)
}
}
// Check for driver.Valuer interface first (takes precedence over type switching)
valueToBind := val.Value
isDriverValue := false
if valuer, ok := val.Value.(driver.Valuer); ok {
driverVal, err := valuer.Value()
if err != nil {
return mapping.StateError, addIndexToError(err, n+1)
}
valueToBind = driverVal
isDriverValue = true
}
switch v := valueToBind.(type) {
case bool:
return mapping.BindBoolean(*s.preparedStmt, mapping.IdxT(n+1), v), nil
case int8:
return mapping.BindInt8(*s.preparedStmt, mapping.IdxT(n+1), v), nil
case int16:
return mapping.BindInt16(*s.preparedStmt, mapping.IdxT(n+1), v), nil
case int32:
return mapping.BindInt32(*s.preparedStmt, mapping.IdxT(n+1), v), nil
case int64:
return mapping.BindInt64(*s.preparedStmt, mapping.IdxT(n+1), v), nil
case int:
// int is at least 32 bits.
return mapping.BindInt64(*s.preparedStmt, mapping.IdxT(n+1), int64(v)), nil
case *big.Int:
if t == TYPE_HUGEINT {
return s.bindHugeint(v, n)
}
if t == TYPE_UHUGEINT {
return s.bindUhugeint(v, n)
}
return s.bindBigNum(v, n)
case Decimal:
// FIXME: use NamedValueChecker to support this type.
name := typeToStringMap[TYPE_DECIMAL]
return mapping.StateError, addIndexToError(unsupportedTypeError(name), n+1)
case uint8:
return mapping.BindUInt8(*s.preparedStmt, mapping.IdxT(n+1), v), nil
case uint16:
return mapping.BindUInt16(*s.preparedStmt, mapping.IdxT(n+1), v), nil
case uint32:
return mapping.BindUInt32(*s.preparedStmt, mapping.IdxT(n+1), v), nil
case uint64:
return mapping.BindUInt64(*s.preparedStmt, mapping.IdxT(n+1), v), nil
case float32:
return mapping.BindFloat(*s.preparedStmt, mapping.IdxT(n+1), v), nil
case float64:
return mapping.BindDouble(*s.preparedStmt, mapping.IdxT(n+1), v), nil
case string:
return mapping.BindVarcharLength(*s.preparedStmt, mapping.IdxT(n+1), v, mapping.IdxT(len(v))), nil
case []byte:
return mapping.BindBlob(*s.preparedStmt, mapping.IdxT(n+1), v), nil
case Interval:
i, inferErr := inferInterval(v)
if inferErr != nil {
return mapping.StateError, inferErr
}
return mapping.BindInterval(*s.preparedStmt, mapping.IdxT(n+1), i), nil
case nil:
return mapping.BindNull(*s.preparedStmt, mapping.IdxT(n+1)), nil
}
// For other types after driver.Valuer conversion, fall back to reflection-based binding
if isDriverValue {
return s.tryBindComplexValue(driver.NamedValue{
Name: val.Name,
Ordinal: val.Ordinal,
Value: valueToBind,
}, n)
}
return s.bindComplexValue(val, n, t, name)
}
func (s *Stmt) bind(args []driver.NamedValue) error {
if s.NumInput() > len(args) {
return fmt.Errorf("incorrect argument count for command: have %d want %d", len(args), s.NumInput())
}
// relaxed length check allow for unused parameters.
for i := range s.NumInput() {
name := mapping.ParameterName(*s.preparedStmt, mapping.IdxT(i+1))
// fallback on index position
arg := args[i]
// override with ordinal if set
for _, v := range args {
if v.Ordinal == i+1 {
arg = v
}
}
// override with name if set
for _, v := range args {
if v.Name == name {
arg = v
}
}
state, err := s.bindValue(arg, i)
if state == mapping.StateError {
errMsg := mapping.PrepareError(*s.preparedStmt)
err = errors.Join(err, getDuckDBError(errMsg))
return errors.Join(errCouldNotBind, err)
}
}
s.bound = true
return nil
}
// Deprecated: Use ExecContext instead.
func (s *Stmt) Exec(args []driver.Value) (driver.Result, error) {
return s.ExecContext(context.Background(), argsToNamedArgs(args))
}
// ExecContext executes a query that doesn't return rows, such as an INSERT or UPDATE.
// It implements the driver.StmtExecContext interface.
func (s *Stmt) ExecContext(ctx context.Context, nargs []driver.NamedValue) (driver.Result, error) {
cleanupCtx := s.conn.setContext(ctx)
defer cleanupCtx()
var res *mapping.Result
if err := runWithCtxInterrupt(ctx, s.conn.conn, func(wctx context.Context) error {
var executeErr error
res, executeErr = s.execute(wctx, nargs)
return executeErr
}); err != nil {
return nil, err
}
defer mapping.DestroyResult(res)
ra := int64(mapping.RowsChanged(res))
return &result{ra}, nil
}
// ColumnCount returns the number of columns that will be returned by executing the prepared statement.
// If any of the column types is invalid (which can happen when the type is ambiguous), the result will be 1.
// Returns an error if the statement is closed or uninitialized.
func (s *Stmt) ColumnCount() (int, error) {
if err := s.checkState(); err != nil {
return 0, err
}
count := mapping.PreparedStatementColumnCount(*s.preparedStmt)
return int(count), nil
}
// ColumnType returns the type of the column at the given index (0-based).
// Returns TYPE_INVALID and a columnIndexError if the column is out of range.
// Returns an error if the statement is closed or uninitialized.
func (s *Stmt) ColumnType(n int) (Type, error) {
if err := s.checkState(); err != nil {
return TYPE_INVALID, err
}
count := mapping.PreparedStatementColumnCount(*s.preparedStmt)
if n < 0 || n >= int(count) {
return TYPE_INVALID, getError(errAPI, columnIndexError(n, uint64(count)))
}
t := mapping.PreparedStatementColumnType(*s.preparedStmt, mapping.IdxT(n))
return t, nil
}
// ColumnTypeInfo returns the TypeInfo of the column at the given index (0-based).
// TypeInfo provides detailed type information including nested structures, DECIMAL precision,
// ENUM values, etc.
// Returns a TypeInfo with internalType TYPE_INVALID and a columnIndexError if the column is out of range.
// Returns an error if the statement is closed or uninitialized.
func (s *Stmt) ColumnTypeInfo(n int) (TypeInfo, error) {
if err := s.checkState(); err != nil {
return nil, err
}
count := mapping.PreparedStatementColumnCount(*s.preparedStmt)
if n < 0 || n >= int(count) {
return nil, getError(errAPI, columnIndexError(n, uint64(count)))
}
lt := mapping.PreparedStatementColumnLogicalType(*s.preparedStmt, mapping.IdxT(n))
defer mapping.DestroyLogicalType(<)
return newTypeInfoFromLogicalType(lt)
}
// ColumnName returns the name of the column at the given index (0-based).
// Returns "" and a columnIndexError if the column is out of range.
// Returns an error if the statement is closed or uninitialized.
func (s *Stmt) ColumnName(n int) (string, error) {
if err := s.checkState(); err != nil {
return "", err
}
count := mapping.PreparedStatementColumnCount(*s.preparedStmt)
if n < 0 || n >= int(count) {
return "", getError(errAPI, columnIndexError(n, uint64(count)))
}
name := mapping.PreparedStatementColumnName(*s.preparedStmt, mapping.IdxT(n))
return name, nil
}
// ExecBound executes a bound query that doesn't return rows, such as an INSERT or UPDATE.
// It can only be used after Bind has been called.
// WARNING: This is a low-level API and should be used with caution.
func (s *Stmt) ExecBound(ctx context.Context) (driver.Result, error) {
if s.closed {
return nil, errClosedCon
}
if s.rows {
return nil, errActiveRows
}
if !s.bound {
return nil, errNotBound
}
cleanupCtx := s.conn.setContext(ctx)
defer cleanupCtx()
var res *mapping.Result
if err := runWithCtxInterrupt(ctx, s.conn.conn, func(wctx context.Context) error {
var executeBoundErr error
res, executeBoundErr = s.executeBound(wctx)
return executeBoundErr
}); err != nil {
return nil, err
}
defer mapping.DestroyResult(res)
ra := int64(mapping.RowsChanged(res))
return &result{ra}, nil
}
// Deprecated: Use QueryContext instead.
func (s *Stmt) Query(args []driver.Value) (driver.Rows, error) {
return s.QueryContext(context.Background(), argsToNamedArgs(args))
}
// QueryContext executes a query that may return rows, such as a SELECT.
// It implements the driver.StmtQueryContext interface.
func (s *Stmt) QueryContext(ctx context.Context, nargs []driver.NamedValue) (driver.Rows, error) {
cleanupCtx := s.conn.setContext(ctx)
defer cleanupCtx()
var res *mapping.Result
if err := runWithCtxInterrupt(ctx, s.conn.conn, func(wctx context.Context) error {
var executeErr error
res, executeErr = s.execute(wctx, nargs)
return executeErr
}); err != nil {
return nil, err
}
s.rows = true
return newRowsWithStmt(*res, s), nil
}
// QueryBound executes a bound query that may return rows, such as a SELECT.
// It can only be used after Bind has been called.
// WARNING: This is a low-level API and should be used with caution.
func (s *Stmt) QueryBound(ctx context.Context) (driver.Rows, error) {
if s.closed {
return nil, errClosedCon
}
if s.rows {
return nil, errActiveRows
}
if !s.bound {
return nil, errNotBound
}
cleanupCtx := s.conn.setContext(ctx)
defer cleanupCtx()
var res *mapping.Result
if err := runWithCtxInterrupt(ctx, s.conn.conn, func(wctx context.Context) error {
var executeBoundErr error
res, executeBoundErr = s.executeBound(wctx)
return executeBoundErr
}); err != nil {
return nil, err
}
s.rows = true
return newRowsWithStmt(*res, s), nil
}
// This method executes the query in steps and checks if context is cancelled before executing each step.
// It uses Pending Result Interface C APIs to achieve this. Reference - https://duckdb.org/docs/api/c/api#pending-result-interface
func (s *Stmt) execute(ctx context.Context, args []driver.NamedValue) (*mapping.Result, error) {
if s.closed {
panic("database/sql/driver: misuse of duckdb driver: ExecContext or QueryContext after Close")
}
if s.rows {
panic("database/sql/driver: misuse of duckdb driver: ExecContext or QueryContext with active Rows")
}
if err := s.BindWithCtx(ctx, args); err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
return s.executeBound(ctx)
}
func (s *Stmt) executeBound(ctx context.Context) (*mapping.Result, error) {
var pendingRes mapping.PendingResult
// Phase 1: create pending result
if mapping.PendingPrepared(*s.preparedStmt, &pendingRes) == mapping.StateError {
dbErr := getDuckDBError(mapping.PendingError(pendingRes))
mapping.DestroyPending(&pendingRes)
return nil, dbErr
}
defer mapping.DestroyPending(&pendingRes)
// Short-circuit before execution
if err := ctx.Err(); err != nil {
return nil, err
}
// Phase 2: execute pending
var res mapping.Result
state := mapping.ExecutePending(pendingRes, &res)
if state == mapping.StateError {
err := errors.Join(ctx.Err(), getDuckDBError(mapping.ResultError(&res)))
mapping.DestroyResult(&res)
return nil, err
}
return &res, nil
}
func argsToNamedArgs(values []driver.Value) []driver.NamedValue {
args := make([]driver.NamedValue, len(values))
for n, param := range values {
args[n].Value = param
args[n].Ordinal = n + 1
}
return args
}