-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patho.go
1485 lines (1382 loc) · 34.6 KB
/
o.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 2016 aletheia7. All rights reserved. Use of this source code is
// governed by a BSD-2-Clause license that can be found in the LICENSE file.
package odb
/*
#cgo CFLAGS: -I${SRCDIR}/odbtp
#cgo LDFLAGS: -L${SRCDIR}/odbtp/.libs -lm -lc -lodbtp
#include <stdlib.h>
#include "odbtp.h"
*/
import "C"
import (
"bytes"
"context"
"database/sql"
"database/sql/driver"
"fmt"
"io"
"net"
"path"
"runtime"
"strconv"
"strings"
"sync/atomic"
"text/template"
"text/template/parse"
"time"
"unsafe"
)
type driver_odbc string
var con_ct, qry_ct int32
const (
Default_port = 2799
// Queries with this prefix will be executed and not prepared
// The prefix is removed
Execute_prefix = `odbexecute`
// Special odbtp query. Use in QueryContext().
// https://docs.microsoft.com/en-us/sql/odbc/reference/develop-app/catalog-functions-in-odbc
Sql_get_type_info = Execute_prefix + "||SQLGetTypeInfo"
Sql_tables = Execute_prefix + "||SQLTables|||"
Sql_columns = Execute_prefix + "||SQLColumns|||" // must append "<table>", and optional "|column"
reset_sql = Execute_prefix + `select 1`
reset_sql_foxpro = Execute_prefix + `set path to`
)
type Login C.odbUSHORT
const (
Normal Login = C.ODB_LOGIN_NORMAL
Reserved = C.ODB_LOGIN_RESERVED
Single = C.ODB_LOGIN_SINGLE
)
type Conn struct {
driver driver_odbc
h C.odbHANDLE
con_ct int32
prepare_is_template bool
zero_scan bool
debug io.Writer
identity_table string
prepare_ctx bool // Called from PrepareContext, else QueryContext
}
func (o *Conn) Prepare(query string) (ds driver.Stmt, err error) {
debug_w(o.debug)
return o.PrepareContext(context.Background(), query)
}
func (o *Conn) PrepareContext(ctx context.Context, query string) (ds driver.Stmt, err error) {
if err = ctx.Err(); err != nil {
return
}
done := make(chan struct{})
go func() {
debug_w(o.debug)
o.prepare_ctx = true
defer close(done)
var st *Stmt
st, err = o.prepare(query)
if err != nil {
return
}
ds = st
debug_w(o.debug)
}()
select {
case <-ctx.Done():
err = ctx.Err()
case <-done:
}
return
}
func (o *Conn) Ping(ctx context.Context) (err error) {
debug_w(o.debug)
return o.ResetSession(ctx)
}
func (o *Conn) ResetSession(ctx context.Context) (err error) {
debug_w(o.debug)
if err = ctx.Err(); err != nil {
return
}
done := make(chan struct{})
go func() {
defer close(done)
var st *Stmt
switch o.driver {
case foxpro:
st, err = o.prepare(reset_sql_foxpro)
default:
st, err = o.prepare(reset_sql)
}
debug_wf(o.debug, "resetsession: o.prepare err: %v\n", err)
if err != nil {
return
}
defer st.Close()
err = st.execute()
debug_wf(o.debug, "resetsession: execute: %v\n", err)
}()
select {
case <-ctx.Done():
err = ctx.Err()
case <-done:
}
debug_wf(o.debug, "resetsession: returned err: %v\n", err)
return
}
func (o *Conn) Close() error {
debug_w(o.debug)
o.logout(true)
return nil
}
func (o *Conn) Begin() (driver.Tx, error) {
return o.BeginTx(context.Background(), driver.TxOptions{})
}
// msaccess: sql.LevelReadCommitted or sql.LevelDefault (usually none)
func (o *Conn) BeginTx(ctx context.Context, opts driver.TxOptions) (tx driver.Tx, err error) {
debug_w(o.debug)
if err = ctx.Err(); err != nil {
return
}
done := make(chan struct{})
go func() {
defer close(done)
if opts.ReadOnly {
err = fmt.Errorf("ReadOnly transaction is not supported")
return
}
var isolation C.odbULONG
switch o.driver {
case msaccess, mssql:
switch sql.IsolationLevel(opts.Isolation) {
case sql.LevelDefault:
isolation = C.ODB_TXN_DEFAULT
case sql.LevelReadUncommitted:
isolation = C.ODB_TXN_READUNCOMMITTED
case sql.LevelReadCommitted:
isolation = C.ODB_TXN_READCOMMITTED
case sql.LevelRepeatableRead:
isolation = C.ODB_TXN_REPEATABLEREAD
case sql.LevelSerializable:
isolation = C.ODB_TXN_SERIALIZABLE
default:
err = fmt.Errorf("unsupported isolation level: %v", opts.Isolation)
return
}
case foxpro:
err = fmt.Errorf("unsupported isolation level: %v", opts.Isolation)
return
default:
err = fmt.Errorf("unkown odbc driver and isolation level")
return
}
if !dB2b(C.odbSetAttrLong(o.h, C.ODB_ATTR_TRANSACTIONS, isolation)) {
err = oe2err(o.h)
return
}
tx = o
}()
select {
case <-ctx.Done():
o.logout(true)
err = ctx.Err()
case <-done:
}
return
}
func (o *Conn) Commit() (err error) {
debug_w(o.debug)
if !dB2b(C.odbCommit(o.h)) {
return oe2err(o.h)
}
return
}
func (o *Conn) Rollback() (err error) {
debug_w(o.debug)
if !dB2b(C.odbRollback(o.h)) {
return oe2err(o.h)
}
return
}
func (o *Conn) Exec(args []driver.Value) (dr driver.Result, err error) {
return nil, driver.ErrSkip
}
func (o *Conn) Query(args []driver.Value) (dr driver.Rows, err error) {
return nil, driver.ErrSkip
}
func (o *Conn) CheckNamedValue(nv *driver.NamedValue) (err error) {
switch t := nv.Value.(type) {
case *int64, *float64, *bool, *[]byte, *string, *time.Time: // These are used for nil
case Identity_table:
o.identity_table = string(t)
err = driver.ErrRemoveArgument
case *Identity_table:
o.identity_table = string(*t)
err = driver.ErrRemoveArgument
case int:
if o.driver == msaccess {
nv.Value = float64(t) // msaccess does not have long/int64
} else {
nv.Value, err = driver.DefaultParameterConverter.ConvertValue(nv.Value)
}
case int64:
if o.driver == msaccess {
nv.Value = float64(t) // msaccess does not have long/int64
} else {
nv.Value, err = driver.DefaultParameterConverter.ConvertValue(nv.Value)
}
default:
nv.Value, err = driver.DefaultParameterConverter.ConvertValue(nv.Value)
}
return
}
type stresult struct {
id int64
id_err error
row int64
row_err error
}
func (o *stresult) LastInsertId() (int64, error) {
return o.id, o.id_err
}
func (o *stresult) RowsAffected() (int64, error) {
return o.row, o.row_err
}
// msaccess: Must add an Identity_table arg to call LastInsertId()
func (o *Conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (dr driver.Result, err error) {
debug_wf(o.debug, query)
if err = ctx.Err(); err != nil {
return
}
done := make(chan struct{})
go func() {
defer close(done)
var st *Stmt
st, err = o.prepare(query)
if err != nil {
return
}
st.identity_table = o.identity_table
_, err = st.QueryContext(ctx, args)
if err != nil {
return
}
r := &stresult{}
r.id, r.id_err = st.LastInsertId()
r.row, r.row_err = st.RowsAffected()
dr = r
st.Close()
}()
select {
case <-ctx.Done():
err = ctx.Err()
case <-done:
}
return
}
func (o *Conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (dr driver.Rows, err error) {
debug_w(o.debug)
if err = ctx.Err(); err != nil {
return
}
done := make(chan struct{})
go func() {
defer close(done)
var st *Stmt
st, err = o.prepare(query)
if err != nil {
return
}
st.identity_table = o.identity_table
dr, err = st.QueryContext(ctx, args)
}()
select {
case <-ctx.Done():
err = ctx.Err()
case <-done:
}
return
}
// host example: pine | pine:2799
func new_con(host string, login Login, dsn string) (r *Conn, err error) {
if !strings.Contains(host, ":") {
host += ":" + strconv.Itoa(Default_port)
}
var tcp *net.TCPAddr
tcp, err = net.ResolveTCPAddr("tcp", host)
if err != nil {
return nil, err
}
r = &Conn{}
switch {
case strings.HasPrefix(dsn, string(msaccess)):
r.driver = msaccess
case strings.HasPrefix(dsn, string(foxpro)):
r.driver = foxpro
case strings.HasPrefix(dsn, string(mssql)):
r.driver = mssql
default:
return nil, fmt.Errorf("unknown driver: %v", dsn)
}
if r.h = C.odbAllocate(nil); r.h == nil {
return nil, driver.ErrBadConn
}
h := new_s(tcp.IP.String())
defer h.free()
p := new_s(dsn)
defer p.free()
if !dB2b(C.odbLogin(r.h, h.p, C.odbUSHORT(tcp.Port), C.odbUSHORT(login), p.p)) {
err = oe2err(r.h)
C.odbFree(r.h)
return nil, driver.ErrBadConn
}
r.con_ct = atomic.AddInt32(&con_ct, 1)
return r, err
}
func (o *Conn) row_cache(enable bool, size uint64) (err error) {
if !dB2b(C.odbUseRowCache(o.h, b2B(enable), C.odbULONG(size))) {
err = oe2err(o.h)
}
return
}
func (o *Conn) get_attr_bool(opt bool_option) (bool, error) {
var long C.odbULONG
if !dB2b(C.odbGetAttrLong(o.h, C.odbLONG(opt), &long)) {
return false, oe2err(o.h)
}
if long == 1 {
return true, nil
}
return false, nil
}
func (o *Conn) set_attr_bool(opt bool_option, enable bool) (err error) {
var long C.odbULONG
if enable {
long = 1
}
if !dB2b(C.odbSetAttrLong(o.h, C.odbLONG(opt), long)) {
err = oe2err(o.h)
}
return
}
func (o *Conn) set_attr_int(opt int_option, i uint64) (err error) {
if !dB2b(C.odbSetAttrLong(o.h, C.odbLONG(opt), C.odbULONG(i))) {
err = oe2err(o.h)
}
return
}
func (o *Conn) logout(disconnect bool) {
if o.h != nil {
C.odbLogout(o.h, b2B(disconnect))
C.odbFree(o.h)
o.h = nil
}
}
func (o *Conn) prepare(query string) (st *Stmt, err error) {
r := &Stmt{
con: o,
bindp: map[C.odbUSHORT]data{},
prepared: true,
qry_ct: atomic.AddInt32(&qry_ct, 1),
}
r.h = C.odbAllocate(o.h)
if r.h == nil {
err = oe2err(o.h)
debug_w(o.debug)
return nil, err
}
debug_wf(o.debug, "con: %v, qry: %v\n", o.con_ct, r.qry_ct)
debug_wf(o.debug, "o.prepare: con: %v, qry: %v query: %v\n", o.con_ct, r.qry_ct, query)
if strings.HasPrefix(query, Execute_prefix) {
r.prepared = false
r.ns = new_named_sql(query[len(Execute_prefix):])
if r.ns.err != nil {
err = r.ns.err
r.Close()
return
}
st = r
return
}
if o.prepare_is_template {
r.ns = new_named_sql(query)
if r.ns.err != nil {
err = r.ns.err
r.Close()
return
}
query = r.ns.sql
}
s := new_s(query)
defer s.free()
if !dB2b(C.odbPrepare(r.h, s.p)) {
err = oe2err(r.h)
r.Close()
return
}
st = r
return
}
type Stmt struct {
con *Conn
h C.odbHANDLE
bindp map[C.odbUSHORT]data
fetch_err error
ns *named_sql
prepared bool
identity_table string // only msaccess
qry_ct int32
}
func (o *Stmt) execute() (err error) {
o.fetch_err = nil
r := false
if o.prepared {
debug_wf(o.con.debug, "execute prepared: %v\n", o.prepared)
r = dB2b(C.odbExecute(o.h, C.odbPCSTR(nil)))
} else {
debug_wf(o.con.debug, "execute not-prepared: %v\n", o.ns.sql)
s := new_s(o.ns.sql)
defer s.free()
r = dB2b(C.odbExecute(o.h, s.p))
}
if !r {
err = oe2err(o.h)
}
return
}
// col: 1 based
func (o *Stmt) bind(col C.odbUSHORT, data data) (err error) {
desc := odb2sql[o.con.driver][data]
if !dB2b(C.odbBindParamEx(
o.h,
col,
C.ODB_PARAM_INPUT,
data.short(),
0,
desc.sql_type,
desc.col_size,
desc.dec_digits,
0,
)) {
return oe2err(o.h)
}
return
}
// col: 1 based
func (o *Stmt) set(col C.odbUSHORT, i interface{}) (err error) {
switch v := i.(type) {
case *[]byte:
if v == nil {
if !dB2b(C.odbSetParamNull(o.h, col, 0)) {
return oe2err(o.h)
}
} else {
s := new_b(*v)
defer s.free()
if !dB2b(C.odbSetParam(o.h, col, (C.odbPVOID)(s.p), C.odbLONG(len(*v)), 0)) {
return oe2err(o.h)
}
}
case []byte:
s := new_b(v)
defer s.free()
if !dB2b(C.odbSetParam(o.h, col, (C.odbPVOID)(s.p), C.odbLONG(len(v)), 0)) {
return oe2err(o.h)
}
case *string:
if v == nil {
if !dB2b(C.odbSetParamNull(o.h, col, 0)) {
return oe2err(o.h)
}
} else {
s := new_s(*v)
defer s.free()
if !dB2b(C.odbSetParam(o.h, col, (C.odbPVOID)(s.p), C.odbLONG(len(*v)), 0)) {
return oe2err(o.h)
}
}
case string:
s := new_s(v)
defer s.free()
if !dB2b(C.odbSetParam(o.h, col, (C.odbPVOID)(s.p), C.odbLONG(len(v)), 0)) {
return oe2err(o.h)
}
case *time.Time:
if v == nil {
if !dB2b(C.odbSetParamNull(o.h, col, 0)) {
return oe2err(o.h)
}
} else {
var ts C.odbTIMESTAMP
ts.sYear = C.odbSHORT(v.Year())
ts.usMonth = C.odbUSHORT(v.Month())
ts.usDay = C.odbUSHORT(v.Day())
ts.usHour = C.odbUSHORT(v.Hour())
ts.usMinute = C.odbUSHORT(v.Minute())
ts.usSecond = C.odbUSHORT(v.Second())
ts.ulFraction = C.odbULONG(v.Nanosecond())
if !dB2b(C.odbSetParamTimestamp(o.h, col, &ts, 0)) {
return oe2err(o.h)
}
}
case time.Time:
var ts C.odbTIMESTAMP
ts.sYear = C.odbSHORT(v.Year())
ts.usMonth = C.odbUSHORT(v.Month())
ts.usDay = C.odbUSHORT(v.Day())
ts.usHour = C.odbUSHORT(v.Hour())
ts.usMinute = C.odbUSHORT(v.Minute())
ts.usSecond = C.odbUSHORT(v.Second())
ts.ulFraction = C.odbULONG(v.Nanosecond())
if !dB2b(C.odbSetParamTimestamp(o.h, col, &ts, 0)) {
return oe2err(o.h)
}
case nil:
if !dB2b(C.odbSetParamNull(o.h, col, 0)) {
return oe2err(o.h)
}
case *int64:
if v == nil {
if !dB2b(C.odbSetParamNull(o.h, col, 0)) {
return oe2err(o.h)
}
} else {
switch o.con.driver {
case msaccess:
if !dB2b(C.odbSetParamDouble(o.h, col, C.odbDOUBLE(float64(*v)), 0)) {
return oe2err(o.h)
}
case foxpro:
if !dB2b(C.odbSetParamLong(o.h, col, C.odbULONG(*v), 0)) {
return oe2err(o.h)
}
default:
if !dB2b(C.odbSetParamLongLong(o.h, col, C.odbULONGLONG(*v), 0)) {
return oe2err(o.h)
}
}
}
case int64:
switch o.con.driver {
case msaccess:
if !dB2b(C.odbSetParamDouble(o.h, col, C.odbDOUBLE(float64(v)), 0)) {
return oe2err(o.h)
}
case foxpro:
if !dB2b(C.odbSetParamLong(o.h, col, C.odbULONG(v), 0)) {
return oe2err(o.h)
}
default:
if !dB2b(C.odbSetParamLongLong(o.h, col, C.odbULONGLONG(v), 0)) {
return oe2err(o.h)
}
}
case *float64:
if v == nil {
if !dB2b(C.odbSetParamNull(o.h, col, 0)) {
return oe2err(o.h)
}
} else {
if !dB2b(C.odbSetParamDouble(o.h, col, C.odbDOUBLE(*v), 0)) {
return oe2err(o.h)
}
}
case float64:
if !dB2b(C.odbSetParamDouble(o.h, col, C.odbDOUBLE(v), 0)) {
return oe2err(o.h)
}
case *bool:
if v == nil {
if !dB2b(C.odbSetParamNull(o.h, col, 0)) {
return oe2err(o.h)
}
} else {
var b C.odbBYTE
if *v {
b = C.odbBYTE(1)
}
if !dB2b(C.odbSetParamByte(o.h, col, b, 0)) {
return oe2err(o.h)
}
}
case bool:
var b C.odbBYTE
if v {
b = C.odbBYTE(1)
}
if !dB2b(C.odbSetParamByte(o.h, col, b, 0)) {
return oe2err(o.h)
}
default:
return fmt.Errorf("invalid type: parama: %v, %T", col, v)
}
return
}
type Rows struct {
*Stmt
}
func (o *Rows) Close() error {
debug_w(o.con.debug)
if !o.con.prepare_ctx {
return o.Stmt.Close()
}
return nil
}
var driver_name_ct uint32
// Returns the registered driver name to use in sql.Open(). The driver name
// pattern is odbtp_msaccess_1, odbtp_msaccess_2, odbtp_msaccess_...
func Register(address string, login Login, odbc_dsn string, opt ...option) (driver_name string) {
switch {
case strings.HasPrefix(odbc_dsn, string(msaccess)):
driver_name = fmt.Sprintf("odbtp_msaccess_%v", atomic.AddUint32(&driver_name_ct, 1))
case strings.HasPrefix(odbc_dsn, string(foxpro)):
driver_name = fmt.Sprintf("odbtp_foxpro_%v", atomic.AddUint32(&driver_name_ct, 1))
case strings.HasPrefix(odbc_dsn, string(mssql)):
driver_name = fmt.Sprintf("odbtp_mssql_%v", atomic.AddUint32(&driver_name_ct, 1))
}
sql.Register(driver_name, &Driver{
addr: address,
login: login,
odbc_dsn: odbc_dsn,
opt: opt,
})
return
}
type option func(o *Conn) error
type bool_option C.odbLONG
const (
// Example in query: {{.id}} becomes sql.Named("id", <value>)
Prepare_is_template bool_option = 1 << iota * -1 // ODB_ATTR are positive
// Zero_scan will cause Stmt.Scan() to return go zero values in place of nil
// for database null
Zero_scan
// http://odbtp.sourceforge.net/clilib.html#attributes
Cache_procs = C.ODB_ATTR_CACHEPROCS
Mapchar2wchar = C.ODB_ATTR_MAPCHARTOWCHAR
Describe_params = C.ODB_ATTR_DESCRIBEPARAMS
Unicodesql = C.ODB_ATTR_UNICODESQL
Right_trim_text = C.ODB_ATTR_RIGHTTRIMTEXT
)
func Bool_opt(opt bool_option, enable bool) option {
return func(o *Conn) error {
switch opt {
case Prepare_is_template:
o.prepare_is_template = enable
case Zero_scan:
o.zero_scan = enable
default:
return o.set_attr_bool(opt, enable)
}
return nil
}
}
func Debug(w io.Writer) option {
return func(o *Conn) error {
o.debug = w
return nil
}
}
type int_option C.odbLONG
const (
Query_timeout int_option = C.ODB_ATTR_QUERYTIMEOUT
Vardatasize = C.ODB_ATTR_VARDATASIZE
)
func Int_opt(opt int_option, i uint64) option {
return func(o *Conn) error {
return o.set_attr_int(opt, i)
}
}
type Driver struct {
addr string
odbc_dsn string
login Login
opt []option
con *Conn
}
// dsn is not used. Use Register()
func (o *Driver) Open(dsn string) (driver.Conn, error) {
if 0 < len(dsn) {
return nil, fmt.Errorf("use Register")
}
if len(o.odbc_dsn) == 0 {
return nil, fmt.Errorf("missing Dsn doption")
}
con, err := new_con(o.addr, o.login, o.odbc_dsn)
if err != nil {
return nil, err
}
if o.opt != nil {
for _, oo := range o.opt {
if err := oo(con); err != nil {
con.logout(true)
return nil, err
}
}
}
debug_w(con.debug)
return con, nil
}
type named_sql struct {
sql string
uniq map[string]string
pos map[int]string
err error
}
func new_named_sql(tp_s string) (r *named_sql) {
r = &named_sql{
uniq: map[string]string{},
pos: map[int]string{},
}
if !strings.Contains(tp_s, "{{") {
r.sql = tp_s
return
}
var tree map[string]*parse.Tree
tree, r.err = parse.Parse(``, tp_s, ``, ``, map[string]interface{}{})
if r.err != nil {
return
}
i := 0
for _, n := range tree[""].Root.Nodes {
if an, ok := n.(*parse.ActionNode); ok {
if an.Pipe == nil {
continue
}
if len(an.Pipe.Cmds) == 1 {
name := an.Pipe.Cmds[0].String()[1:] // remove dot
r.uniq[name] = `?`
r.pos[i] = name
i++
}
}
}
var buf bytes.Buffer
tp := template.Must(template.New(``).Option("missingkey=error").Parse(tp_s))
r.err = tp.Execute(&buf, r.uniq)
r.sql = buf.String()
return
}
func (o *Stmt) Close() error {
debug_wf(o.con.debug, "con: %v, qry: %v", o.con.con_ct, o.qry_ct)
if o.h != nil {
C.odbDropQry(o.h)
C.odbFree(o.h)
o.h = nil
o.bindp = map[C.odbUSHORT]data{}
}
return nil
}
func (o *Stmt) NumInput() int {
if o.ns != nil && 0 < len(o.ns.uniq) {
return len(o.ns.uniq)
}
return int(C.odbGetTotalParams(o.h))
}
// Only usefull with msaccess
func (o *Stmt) LastInsertId() (id int64, err error) {
if o.con.driver != msaccess {
return 0, driver.ErrSkip
}
if len(o.identity_table) == 0 {
return 0, fmt.Errorf("missing Identity_table arg")
}
st, err := o.con.prepare(fmt.Sprintf("select @@IDENTITY from [%v]", o.identity_table))
if err != nil {
return
}
defer st.Close()
if err = st.execute(); err != nil {
return
}
dv := make([]driver.Value, 1)
if err = st.Next(dv); err != nil {
return
}
var ok bool
id, ok = dv[0].(int64)
if !ok {
return 0, fmt.Errorf("could not convert %v (%T) to int64", dv[0], dv[0])
}
return
}
func (o *Stmt) RowsAffected() (i int64, err error) {
i = int64(C.odbGetRowCount(o.h))
if i == 0 {
if 0 < int(C.odbGetError(o.h)) {
err = oe2err(o.h)
}
}
return
}
func (o *Stmt) Exec(args []driver.Value) (dr driver.Result, err error) {
return nil, driver.ErrSkip
}
func (o *Stmt) Query(args []driver.Value) (dr driver.Rows, err error) {
return nil, driver.ErrSkip
}
// Used with msaccess. See ExecContext()
type Identity_table string
func (o *Stmt) CheckNamedValue(nv *driver.NamedValue) (err error) {
switch t := nv.Value.(type) {
case *int64, *float64, *bool, *[]byte, *string, *time.Time: // These are used for nil
case Identity_table:
o.identity_table = string(t)
err = driver.ErrRemoveArgument
case *Identity_table:
o.identity_table = string(*t)
err = driver.ErrRemoveArgument
case int:
if o.con.driver == msaccess {
nv.Value = float64(t) // msaccess does not have long/int64
} else {
nv.Value, err = driver.DefaultParameterConverter.ConvertValue(nv.Value)
}
case int64:
if o.con.driver == msaccess {
nv.Value = float64(t) // msaccess does not have long/int64
} else {
nv.Value, err = driver.DefaultParameterConverter.ConvertValue(nv.Value)
}
default:
nv.Value, err = driver.DefaultParameterConverter.ConvertValue(nv.Value)
}
return
}
var (
// string or []byte input parameter to be set to database null
Ns *string
// int64 input parameter to be set to database null
Ni *int64
// float64 input parameter to be set to database null
Nf *float64
// bool input parameter to be set to database null
Nb *bool
// time.Time input parameter to be set to database null
Nt *time.Time
)
// msaccess: Must add an Identity_table arg to call LastInsertId()
func (o *Stmt) ExecContext(ctx context.Context, args []driver.NamedValue) (dr driver.Result, err error) {
debug_w(o.con.debug)
_, err = o.QueryContext(ctx, args)
if err == nil {
dr = o
}
return
}
func (o *Stmt) QueryContext(ctx context.Context, args []driver.NamedValue) (dr driver.Rows, err error) {
debug_w(o.con.debug)
if err = ctx.Err(); err != nil {
return
}
done := make(chan struct{})
go func() {
defer close(done)
var col C.odbUSHORT
if o.ns != nil && 0 < len(o.ns.uniq) {
args, err = o.named2pos(args)
if err != nil {
return
}
}
for _, na := range args {
col++
switch t := na.Value.(type) {
case string, *string, []byte, *[]byte, nil:
if o.con.driver == foxpro {
err = o.bind(col, ochar)
} else {
err = o.bind(col, owchar)
}
case int64, *int64:
switch o.con.driver {
case foxpro:
err = o.bind(col, oint)
default:
err = o.bind(col, obigint)
}
case time.Time, *time.Time:
err = o.bind(col, odatetime)
case bool, *bool:
err = o.bind(col, obit)
case float64, *float64:
err = o.bind(col, odouble)
default:
err = fmt.Errorf("type unsupported: %T %v %v %v", t, na.Ordinal, na.Name, na.Value)
}
if err != nil {
return
}
}
if 0 < col && !dB2b(C.odbFinalizeRequest(o.h)) {
err = oe2err(o.h)
return
}
col = 0
for _, v := range args {
col++
if err = o.set(col, v.Value); err != nil {
return
}
}
if 0 < col && !dB2b(C.odbFinalizeRequest(o.h)) {
err = oe2err(o.h)
return
}
if err = o.execute(); err != nil {
return
}
dr = &Rows{o}
}()
select {
case <-ctx.Done():
err = ctx.Err()
case <-done: