/
odbcdriver.go
1935 lines (1689 loc) · 52.8 KB
/
odbcdriver.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
package main
import (
"encoding/binary"
"encoding/json"
"fmt"
"net/http"
"os"
"reflect"
"regexp"
"runtime/cgo"
"sort"
"strconv"
"strings"
"time"
"unicode/utf16"
"unsafe"
"github.com/rs/zerolog"
"golang.org/x/exp/constraints"
"golang.org/x/sync/errgroup"
)
// #if defined(_WIN32)
// #include <windows.h>
// #endif
// #include <stdint.h>
// #include <stdlib.h>
// #include <string.h>
// #include <sqltypes.h>
// #include <sql.h>
// #include <sqlext.h>
import "C"
var (
Version string = "dev"
Commit string = "?"
BuildDate string = "?"
LogFile string = ""
LogFormat string = ""
LogLevel string = ""
)
func Convert(value any, t string) (any, error) {
switch t {
case "int":
case "float":
case "string":
case "":
return value, nil
default:
return nil, fmt.Errorf("invalid destination type %s", t)
}
switch v := value.(type) {
case int64:
switch t {
case "int":
return v, nil
case "float":
return float64(v), nil
case "string":
return strconv.FormatInt(v, 10), nil
}
case float64:
switch t {
case "int":
return int64(v), nil
case "float":
return v, nil
case "string":
return strconv.FormatFloat(v, 'G', -1, 64), nil
}
case string:
switch t {
case "int":
return strconv.ParseInt(v, 0, 64)
case "float":
return strconv.ParseFloat(v, 64)
case "string":
return v, nil
}
case bool:
switch t {
case "int":
if v {
return 1, nil
}
return 0, nil
case "float":
if v {
return 1.0, nil
}
return 0.0, nil
case "string":
if v {
return "1", nil
}
return "0", nil
}
}
return nil, fmt.Errorf("unknown source type %T for value %v", value, value)
}
func toGoString[T C.int | C.short | C.long](str *C.SQLCHAR, len T) string {
if str == nil {
return ""
}
if len == C.SQL_NTS {
return C.GoString((*C.char)(unsafe.Pointer(str)))
}
return C.GoStringN((*C.char)(unsafe.Pointer(str)), C.int(len))
}
func setupLogging(log zerolog.Logger, logFile, logFormat, logLevel string) zerolog.Logger {
if logFile != "" {
file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
fmt.Printf("Error setting up logging: %s", err)
}
if file != nil {
if logFormat == "pretty" {
output := zerolog.ConsoleWriter{Out: file, TimeFormat: time.RFC3339}
log = log.Output(output)
} else {
log = log.Output(file)
}
}
}
switch strings.ToLower(logLevel) {
case "debug":
log = log.Level(zerolog.DebugLevel)
case "info":
log = log.Level(zerolog.InfoLevel)
case "warn":
log = log.Level(zerolog.WarnLevel)
case "error":
log = log.Level(zerolog.ErrorLevel)
case "fatal":
log = log.Level(zerolog.FatalLevel)
case "panic":
log = log.Level(zerolog.PanicLevel)
case "none":
log = log.Level(zerolog.NoLevel)
case "disabled":
log = log.Level(zerolog.Disabled)
case "trace":
log = log.Level(zerolog.TraceLevel)
default:
log = log.Level(zerolog.InfoLevel)
}
return log
}
func (connHandle *connectionHandle) initConnection(dsn, connectionString, userName, password string) C.SQLRETURN {
args := make(map[string]string)
for _, arg := range strings.Split(connectionString, ";") {
sarg := strings.SplitN(arg, "=", 2)
if len(sarg) == 1 {
args[strings.ToLower(sarg[0])] = ""
} else {
args[strings.ToLower(sarg[0])] = sarg[1]
}
}
conStrArg := func(arg, defaultValue string) string {
if value, ok := args[arg]; ok {
return value
}
return defaultValue
}
dsn = conStrArg("dsn", dsn)
var fetchParametersStr, fetchMetadataStr, logFile, logFormat, logLevel, httpTimeout string
// Config file is lowest priority
if dsn != "" {
connHandle.inventreeConfig.server = SQLGetPrivateProfileString(dsn, "server", "", ".odbc.ini")
connHandle.inventreeConfig.userName = SQLGetPrivateProfileString(dsn, "username", "", ".odbc.ini")
connHandle.inventreeConfig.password = SQLGetPrivateProfileString(dsn, "password", "", ".odbc.ini")
connHandle.inventreeConfig.apiToken = SQLGetPrivateProfileString(dsn, "apitoken", "", ".odbc.ini")
fetchParametersStr = SQLGetPrivateProfileString(dsn, "apitoken", "", ".odbc.ini")
fetchMetadataStr = SQLGetPrivateProfileString(dsn, "apitoken", "", ".odbc.ini")
logFile = SQLGetPrivateProfileString(dsn, "logfile", "", ".odbc.ini")
logFormat = SQLGetPrivateProfileString(dsn, "logformat", "", ".odbc.ini")
logLevel = SQLGetPrivateProfileString(dsn, "loglevel", "", ".odbc.ini")
httpTimeout = SQLGetPrivateProfileString(dsn, "httptimeout", "", ".odbc.ini")
}
// Then connection string is higher
connHandle.inventreeConfig.server = conStrArg("server", connHandle.inventreeConfig.server)
connHandle.inventreeConfig.userName = conStrArg("username", connHandle.inventreeConfig.userName)
connHandle.inventreeConfig.password = conStrArg("password", connHandle.inventreeConfig.password)
connHandle.inventreeConfig.apiToken = conStrArg("apitoken", connHandle.inventreeConfig.apiToken)
fetchParametersStr = conStrArg("fetchparameters", fetchParametersStr)
fetchMetadataStr = conStrArg("fetchparameters", fetchMetadataStr)
logFile = conStrArg("logfile", logFile)
logFormat = strings.ToLower(conStrArg("logformat", logFormat))
logLevel = strings.ToLower(conStrArg("loglevel", logLevel))
httpTimeout = strings.ToLower(conStrArg("httptimeout", httpTimeout))
if LogFile == "" {
connHandle.log = setupLogging(connHandle.log, logFile, logFormat, logLevel)
}
log := connHandle.log.With().Str("fn", "initConnection").Dict("args", zerolog.Dict().Str("dsn", dsn).Str("connectionString", connectionString).Str("userName", userName).Str("password", password)).Logger()
log.Debug().Send()
httpTimeoutDuration := 30 * time.Second
if httpTimeout != "" {
var err error
httpTimeoutDuration, err = time.ParseDuration(httpTimeout)
if err != nil {
log.Error().Err(err).Msgf("Error parsing httptimeout, default timeout used: %s", httpTimeoutDuration)
}
}
connHandle.httpClient = &http.Client{Timeout: httpTimeoutDuration}
// Explicit username and password is highest
if userName != "" {
connHandle.inventreeConfig.userName = userName
}
if password != "" {
connHandle.inventreeConfig.password = password
}
switch strings.ToLower(fetchParametersStr) {
case "yes":
connHandle.inventreeConfig.fetchParameters = true
case "no":
connHandle.inventreeConfig.fetchParameters = false
case "":
connHandle.inventreeConfig.fetchParameters = true
default:
return SetAndReturnError(connHandle, &DriverError{SqlState: "08001", Message: "fetchParameters accepts 'yes' or 'no"})
}
switch strings.ToLower(fetchMetadataStr) {
case "yes":
connHandle.inventreeConfig.fetchMetadata = true
case "no":
connHandle.inventreeConfig.fetchMetadata = false
case "":
connHandle.inventreeConfig.fetchMetadata = false
default:
return SetAndReturnError(connHandle, &DriverError{SqlState: "08001", Message: "fetchMetadata accepts 'yes' or 'no"})
}
if connHandle.inventreeConfig.server == "" {
return SetAndReturnError(connHandle, &DriverError{SqlState: "08001", Message: "No Server specified"})
}
connHandle.inventreeConfig.server = strings.TrimSuffix(connHandle.inventreeConfig.server, "/")
if connHandle.inventreeConfig.apiToken == "" && (connHandle.inventreeConfig.userName == "" || connHandle.inventreeConfig.password == "") {
return SetAndReturnError(connHandle, &DriverError{SqlState: "08001", Message: "No APIToken or Username+Password specified"})
}
if connHandle.inventreeConfig.apiToken == "" {
var token string
token, err := connHandle.getApiToken(connHandle.inventreeConfig.userName, connHandle.inventreeConfig.password) // why pass these?
if err != nil {
return SetAndReturnError(connHandle, &DriverError{SqlState: "08001", Message: "Failed to fetch API Token", Err: err})
}
connHandle.inventreeConfig.apiToken = token
}
if err := connHandle.updateCategoryMapping(); err != nil {
return SetAndReturnError(connHandle, &DriverError{SqlState: "08001", Message: "Error updating category list", Err: err})
}
return C.SQL_SUCCESS
}
func resolveHandle(handle C.SQLHANDLE) any {
defer func() { recover() }()
return cgo.Handle(handle).Value()
}
func resolveConnectionHandle(handle C.SQLHDBC) *connectionHandle {
defer func() { recover() }()
return cgo.Handle(handle).Value().(*connectionHandle)
}
func resolveStatementHandle(handle C.SQLHSTMT) *statementHandle {
defer func() { recover() }()
return cgo.Handle(handle).Value().(*statementHandle)
}
//export SQLConnect
func SQLConnect(ConnectionHandle C.SQLHDBC,
ServerName *C.SQLCHAR, NameLength1 C.SQLSMALLINT,
UserName *C.SQLCHAR, NameLength2 C.SQLSMALLINT,
Authentication *C.SQLCHAR, NameLength3 C.SQLSMALLINT,
) C.SQLRETURN {
connHandle := resolveConnectionHandle(ConnectionHandle)
if connHandle == nil {
return C.SQL_INVALID_HANDLE
}
serverName := toGoString(ServerName, NameLength1)
userName := toGoString(UserName, NameLength2)
password := toGoString(Authentication, NameLength3)
return connHandle.initConnection(serverName, "", userName, password)
}
//export SQLDriverConnect
func SQLDriverConnect(
ConnectionHandle C.SQLHDBC,
WindowHandle C.SQLHWND,
InConnectionString *C.SQLCHAR,
StringLength1 C.SQLSMALLINT,
OutConnectionString *C.SQLCHAR,
BufferLength C.SQLSMALLINT,
StringLength2Ptr *C.SQLSMALLINT,
DriverCompletion C.SQLUSMALLINT,
) C.SQLRETURN {
connHandle := resolveConnectionHandle(ConnectionHandle)
if connHandle == nil {
return C.SQL_INVALID_HANDLE
}
inConnectionString := toGoString(InConnectionString, StringLength1)
return connHandle.initConnection("", inConnectionString, "", "")
}
type DriverError struct {
SqlState string
NativeError string
Message string
Err error
}
func (e *DriverError) Error() string { return e.SqlState + ": " + e.Message }
func (e *DriverError) Unwrap() error { return e.Err }
func (e *DriverError) SetAndReturnError(handle errorInfo) C.SQLRETURN {
handle.errorInfo = e
return C.SQL_ERROR
}
func getLogger(handle interface{}) zerolog.Logger {
switch h := handle.(type) {
case *environmentHandle:
return zerolog.Logger{}
case *connectionHandle:
return h.log
case *statementHandle:
return h.log
default:
return zerolog.Logger{}
}
}
func SetError(handle interface{}, err *DriverError) zerolog.Logger {
switch h := handle.(type) {
// These are all the same really:
// case C.SQLHENV:
// case C.SQLHDBC:
// case C.SQLHSTMT:
case C.SQLHANDLE:
handle = cgo.Handle(h).Value()
}
switch h := handle.(type) {
case *environmentHandle:
h.errorInfo.errorInfo = err
return zerolog.Logger{}
case *connectionHandle:
h.errorInfo.errorInfo = err
return h.log
case *statementHandle:
h.errorInfo.errorInfo = err
return h.log
default:
return zerolog.Logger{}
}
}
func SetAndReturnError(handle interface{}, err *DriverError) C.SQLRETURN {
log := SetError(handle, err)
log.Error().Err(err).Str("return", "SQL_ERROR").Send()
return C.SQL_ERROR
}
type errorInfo struct {
errorInfo *DriverError
}
type logging struct {
log zerolog.Logger
}
type environmentHandle struct {
errorInfo
}
func (e *environmentHandle) init() {
}
func addressBytes(addr unsafe.Pointer) []byte {
buf := make([]byte, binary.MaxVarintLen64)
binary.BigEndian.PutUint64(buf, uint64(uintptr(addr)))
return buf
}
func (e *environmentHandle) MarshalZerologObject(ev *zerolog.Event) {
ev.Hex("handle_env", addressBytes(unsafe.Pointer(e)))
}
type connectionHandle struct {
errorInfo
logging
httpClient *http.Client
env *environmentHandle
inventreeConfig struct {
server string
userName string
password string
apiToken string
fetchParameters bool
fetchMetadata bool
}
categoryMapping map[string]int
// This cache isn't ideal because it never expires. However, for KiCad
// I don't think it matters much, since KiCad will refresh its full list
// of parts before individual parts can be selected, which means this
// cache should be up to date with what parts can actually be selected.
ipnToPkMap map[string]any
}
func (c *connectionHandle) init(envHandle *environmentHandle) {
c.env = envHandle
c.log = zerolog.Nop().With().Timestamp().EmbedObject(c).Logger()
if LogFile != "" {
c.log = setupLogging(c.log, LogFile, LogFormat, LogLevel)
}
}
func (c *connectionHandle) MarshalZerologObject(e *zerolog.Event) {
e.EmbedObject(c.env).Hex("handle_conn", addressBytes(unsafe.Pointer(c)))
}
func (c *connectionHandle) updateIpnToPkMap(parts *[]map[string]any) error {
if c.ipnToPkMap == nil {
c.ipnToPkMap = make(map[string]any)
}
for _, part := range *parts {
if part["IPN"] == nil {
continue
}
number, ok := part["pk"].(json.Number)
if !ok {
return fmt.Errorf("'pk' is not a number: %q", part["pk"])
}
pk, err := number.Int64()
if err != nil {
return fmt.Errorf("was unable to convert 'pk' to an int64: %v", part["pk"])
}
ipn := part["IPN"].(string)
if ipn == "" {
continue
}
c.ipnToPkMap[ipn] = pk
}
return nil
}
func (c *connectionHandle) getApiToken(userName, password string) (string, error) {
request, err := http.NewRequest("GET", c.inventreeConfig.server+"/api/user/token", nil)
if err != nil {
return "", err
}
request.SetBasicAuth(userName, password)
response, err := c.httpClient.Do(request)
if err != nil {
return "", err
}
if response.StatusCode != 200 {
return "", fmt.Errorf("unexpected status code %s", response.Status)
}
type Token struct {
Token string `json:"token"`
}
decoder := json.NewDecoder(response.Body)
val := &Token{}
err = decoder.Decode(val)
if err != nil {
return "", err
}
return val.Token, nil
}
func (c *connectionHandle) apiGet(resource string, args map[string]string, result any) error {
request, err := http.NewRequest("GET", c.inventreeConfig.server+resource, nil)
if err != nil {
return err
}
request.Header.Add("Authorization", fmt.Sprintf("Token %s", c.inventreeConfig.apiToken))
if args != nil {
q := request.URL.Query()
for key, val := range args {
q.Add(key, val)
}
request.URL.RawQuery = q.Encode()
}
response, err := c.httpClient.Do(request)
if err != nil {
return err
}
if response.StatusCode != 200 {
return fmt.Errorf("unexpected status code %s", response.Status)
}
decoder := json.NewDecoder(response.Body)
decoder.UseNumber()
err = decoder.Decode(result)
if err != nil {
return err
}
return nil
}
func (c *connectionHandle) updateCategoryMapping() error {
type category struct {
Pk int `json:"pk"`
Pathstring string `json:"pathstring"`
}
categories := []category{}
if err := c.apiGet("/api/part/category/", nil, &categories); err != nil {
return err
}
c.categoryMapping = make(map[string]int)
for _, category := range categories {
c.categoryMapping[category.Pathstring] = category.Pk
}
return nil
}
func keys[K comparable, V any](m map[K]V) []K {
keys := make([]K, 0, len(m))
for k := range m {
keys = append(keys, k)
}
return keys
}
func (s *statementHandle) fetchAllParts(category string, parts *[]map[string]any) error {
args := make(map[string]string)
categoryId, ok := s.conn.categoryMapping[category]
if !ok {
return &DriverError{SqlState: "HY000", Message: fmt.Sprintf("Category does not exist in InvenTree: %s", category)}
}
args["category"] = strconv.Itoa(categoryId)
return s.conn.apiGet("/api/part/", args, parts)
}
func mangleParameters(params []map[string]any) map[string]any {
result := make(map[string]any)
for _, param := range params {
name := param["template_detail"].(map[string]any)["name"].(string)
data := param["data"].(string)
result[name] = data
}
return result
}
func (s *statementHandle) fetchPart(category string, column string, value any, parts *[]map[string]any) error {
var part map[string]any
var partMetadata map[string]any
var partParameters map[string]any
var pkValue any
switch column {
case "pk":
pkValue = value
case "IPN":
if s.conn.ipnToPkMap == nil {
var tmpParts []map[string]any
if err := s.fetchAllParts(category, &tmpParts); err != nil {
return err
}
if err := s.conn.updateIpnToPkMap(&tmpParts); err != nil {
return err
}
}
var ok bool
if pkValue, ok = s.conn.ipnToPkMap[value.(string)]; !ok {
return nil
}
// XXX: could optimise away the next fetch of parts, since we should already
// have had the the required part returned when fetching all parts.
// but this is not a path that should ever be hit when fetching from KiCad.
// This is mostly to make running manual queries not annoying.
default:
return fmt.Errorf("invalid filter column: %s", column)
}
getPart := func() error {
if err := s.conn.apiGet(fmt.Sprintf("/api/part/%v/", pkValue), nil, &part); err != nil {
return err
}
return nil
}
g := new(errgroup.Group)
g.Go(getPart)
if s.conn.inventreeConfig.fetchMetadata {
g.Go(func() error {
if err := s.conn.apiGet(fmt.Sprintf("/api/part/%v/metadata/", pkValue), nil, &partMetadata); err != nil {
return err
}
return nil
})
}
if s.conn.inventreeConfig.fetchParameters {
g.Go(func() error {
var rawPartParameters []map[string]any
args := make(map[string]string)
value, _ := Convert(pkValue, "string") // maybe just sprintf?
args["part"] = value.(string)
if err := s.conn.apiGet("/api/part/parameter/", args, &rawPartParameters); err != nil {
return err
}
partParameters = mangleParameters(rawPartParameters)
return nil
})
}
if err := g.Wait(); err != nil {
return err
}
var flatten func(string, map[string]any)
flatten = func(path string, data map[string]any) {
for key, value := range data {
if path == "" {
key = key
} else {
key = path + "." + key
}
if value == nil {
part[key] = value // ???
continue
}
switch reflect.TypeOf(value).Kind().String() {
case "array":
continue
case "map":
flatten(key, value.(map[string]any))
default:
part[key] = value
}
}
}
if partMetadata != nil {
flatten("", partMetadata)
}
for key, parameter := range partParameters {
part["parameter."+key] = parameter
}
*parts = append(*parts, part)
return nil
}
func (s *statementHandle) populateColDesc(data *[]map[string]any) {
columns := make(map[string]*desc)
for _, row := range *data {
for key := range row {
if _, ok := columns[key]; !ok {
size := 0 // See: http://www.ch-werner.de/sqliteodbc/html/sqlite3odbc_8c.html#a107
var dataType C.short
switch value := row[key].(type) {
case json.Number:
if _, err := value.Int64(); err == nil {
dataType = C.SQL_BIGINT
size = 20
} else if _, err := value.Float64(); err == nil {
dataType = C.SQL_DOUBLE
size = 54
}
case string:
dataType = C.SQL_VARCHAR
size = 255
case float64:
dataType = C.SQL_DOUBLE
size = 54
case bool:
dataType = C.SQL_INTEGER
size = 10
}
columns[key] = &desc{name: key, dataType: dataType, colSize: size, nullable: C.SQL_NULLABLE}
}
}
}
s.columnNames = keys(columns)
sort.Strings(s.columnNames)
for _, name := range s.columnNames {
s.def = append(s.def, columns[name])
}
}
func (s *statementHandle) populateData(data *[]map[string]any) {
for _, row := range *data {
rowData := make([]any, len(s.def))
for idx, colName := range s.columnNames {
if value, ok := row[colName]; ok {
rowData[idx] = value
}
}
s.data = append(s.data, rowData)
}
}
type bind struct {
TargetType C.SQLSMALLINT
TargetValuePtr C.SQLPOINTER
BufferLength C.SQLLEN
StrLen_or_IndPtr *C.SQLLEN
}
type param struct {
ValueType C.SQLSMALLINT
ParameterValuePtr C.SQLPOINTER
BufferLength C.SQLLEN
}
type desc struct {
name string
dataType C.short
colSize int
decimalDigits int
nullable int
}
type cond struct {
column string
value string
}
type stmt struct {
table string
condition *cond
}
type statementHandle struct {
errorInfo
logging
conn *connectionHandle
columnNames []string
def []*desc
binds []*bind
params []*param
data [][]any
index int
rowsFetchedPtr *C.SQLULEN
statement *stmt
}
func (s *statementHandle) init(connHandle *connectionHandle) {
s.conn = connHandle
s.index = -1
s.log = connHandle.log.With().Hex("handle_stmt", addressBytes(unsafe.Pointer(s))).Logger()
}
func (s *statementHandle) populateBinds() {
for idx, bind := range s.binds {
if bind == nil {
continue
}
value := s.data[s.index][idx]
populateData(value, bind.TargetType, bind.TargetValuePtr, bind.BufferLength, bind.StrLen_or_IndPtr)
}
}
func copyGoStringToCString(dst *C.uchar, src string, length int) {
cSrc := C.CString(src + "\x00")
defer C.free(unsafe.Pointer(cSrc))
C.strncpy((*C.char)(unsafe.Pointer(dst)), cSrc, C.size_t(length)+1) // + 1 because we add "\0"
}
func copyStringToBuffer(dst *C.uchar, src string, bufferSize int) int {
if len(src)+1 > bufferSize {
src = src[:bufferSize-1]
}
cSrc := C.CString(src + "\x00")
defer C.free(unsafe.Pointer(cSrc))
length := len(src) + 1
C.strncpy((*C.char)(unsafe.Pointer(dst)), cSrc, C.size_t(length))
return length
}
//export SQLGetDiagRec
func SQLGetDiagRec(
HandleType C.SQLSMALLINT,
Handle C.SQLHANDLE,
RecNumber C.SQLSMALLINT,
SQLState *C.SQLCHAR,
NativeErrorPtr *C.SQLINTEGER,
MessageText *C.SQLCHAR,
BufferLength C.SQLSMALLINT,
TextLengthPtr *C.SQLSMALLINT,
) C.SQLRETURN {
var errorInfo *DriverError
var log zerolog.Logger
genericHandle := resolveHandle(Handle)
switch handle := genericHandle.(type) {
case *environmentHandle:
if HandleType != C.SQL_HANDLE_ENV {
return C.SQL_INVALID_HANDLE
}
errorInfo = handle.errorInfo.errorInfo
log = zerolog.Logger{}
case *connectionHandle:
if HandleType != C.SQL_HANDLE_DBC {
return C.SQL_INVALID_HANDLE
}
errorInfo = handle.errorInfo.errorInfo
log = handle.log.With().Str("fn", "SQLGetDiagRec").Str("handle_type", "SQL_HANDLE_DBC").Hex("handle", addressBytes(unsafe.Pointer(handle))).Logger()
case *statementHandle:
if HandleType != C.SQL_HANDLE_STMT {
return C.SQL_INVALID_HANDLE
}
errorInfo = handle.errorInfo.errorInfo
log = handle.log.With().Str("fn", "SQLGetDiagRec").Str("handle_type", "SQL_HANDLE_STMT").Hex("handle", addressBytes(unsafe.Pointer(handle))).Logger()
default:
return C.SQL_INVALID_HANDLE
}
/* On Windows 10 (at least, but not 11) these have to be zeroed
even when returning SQL_NO_DATA
*/
if SQLState != nil {
*SQLState = 0
}
if NativeErrorPtr != nil {
*NativeErrorPtr = 0
}
if MessageText != nil && BufferLength > 0 {
*MessageText = 0
}
if TextLengthPtr != nil {
*TextLengthPtr = 0
}
if errorInfo == nil {
log.Debug().Msg("errInfo was nil")
return C.SQL_NO_DATA
}
if RecNumber < 1 {
log.Debug().Msgf("RecNumber:%v < 1", RecNumber)
return C.SQL_ERROR
}
if RecNumber != 1 {
log.Debug().Msgf("RecNumber:%v != 1", RecNumber)
return C.SQL_NO_DATA
}
var message string
if errorInfo.Err != nil {
message = fmt.Sprintf("%s: %s", errorInfo.Message, errorInfo.Err)
} else {
message = errorInfo.Message
}
copyStringToBuffer(SQLState, errorInfo.SqlState, 6) // 5 + \x00
if MessageText != nil {
copyStringToBuffer(MessageText, message, int(BufferLength))
}
*TextLengthPtr = C.short(len(message))
return C.SQL_SUCCESS
}
//export SQLGetDiagField
func SQLGetDiagField(
HandleType C.SQLSMALLINT,
Handle C.SQLHANDLE,
RecNumber C.SQLSMALLINT,
DiagIdentifier C.SQLSMALLINT,
DiagInfoPtr C.SQLPOINTER,
BufferLength C.SQLSMALLINT,
StringLengthPtr *C.SQLSMALLINT,
) C.SQLRETURN {
var errorInfo *DriverError
var log zerolog.Logger
genericHandle := resolveHandle(Handle)
switch handle := genericHandle.(type) {
case *environmentHandle:
if HandleType != C.SQL_HANDLE_ENV {
return C.SQL_INVALID_HANDLE
}
errorInfo = handle.errorInfo.errorInfo
log = zerolog.Logger{}
case *connectionHandle:
if HandleType != C.SQL_HANDLE_DBC {
return C.SQL_INVALID_HANDLE
}
errorInfo = handle.errorInfo.errorInfo
log = handle.log.With().Str("fn", "SQLGetDiagField").Str("handle_type", "SQL_HANDLE_DBC").Hex("handle", addressBytes(unsafe.Pointer(handle))).Logger()
case *statementHandle:
if HandleType != C.SQL_HANDLE_STMT {
return C.SQL_INVALID_HANDLE
}
errorInfo = handle.errorInfo.errorInfo
log = handle.log.With().Str("fn", "SQLGetDiagField").Str("handle_type", "SQL_HANDLE_STMT").Hex("handle", addressBytes(unsafe.Pointer(handle))).Logger()
default:
return C.SQL_INVALID_HANDLE
}
if errorInfo == nil {
log.Debug().Msg("errInfo was nil")
return C.SQL_NO_DATA
}
if RecNumber < 1 {
log.Debug().Msgf("RecNumber:%v < 1", RecNumber)
return C.SQL_ERROR
}
if RecNumber != 1 {
log.Debug().Msgf("RecNumber:%v != 1", RecNumber)
return C.SQL_NO_DATA
}
copyString := func(msg string) C.SQLRETURN {
copied := copyStringToBuffer((*C.SQLCHAR)(DiagInfoPtr), msg, int(BufferLength))
*StringLengthPtr = C.SQLSMALLINT(copied - 1) // - \x00
if copied-1 != len(msg) { // - \x00
return C.SQL_SUCCESS_WITH_INFO
}
return C.SQL_SUCCESS
}
switch DiagIdentifier {
case C.SQL_DIAG_NUMBER:
log.Debug().Str("DiagIdentifier", "SQL_DIAG_NUMBER").Int("DiagInfoPtr", 1).Str("return", "SQL_SUCCESS").Send()
*((*C.SQLINTEGER)(DiagInfoPtr)) = 1
return C.SQL_SUCCESS
case C.SQL_DIAG_NATIVE:
log.Debug().Str("DiagIdentifier", "SQL_DIAG_NATIVE").Int("DiagInfoPtr", 0).Str("return", "SQL_SUCCESS").Send()
*((*C.SQLINTEGER)(DiagInfoPtr)) = 0
return C.SQL_SUCCESS
case C.SQL_DIAG_SQLSTATE:
log.Debug().Str("DiagIdentifier", "SQL_DIAG_SQLSTATE").Str("DiagInfoPtr", errorInfo.SqlState).Str("return", "SQL_SUCCESS").Send()
return copyString(errorInfo.SqlState)
case C.SQL_DIAG_MESSAGE_TEXT:
var message string
if errorInfo.Err != nil {
message = fmt.Sprintf("%s: %s", errorInfo.Message, errorInfo.Err)
} else {
message = errorInfo.Message