-
Notifications
You must be signed in to change notification settings - Fork 54
/
connection.go
1236 lines (1058 loc) · 34 KB
/
connection.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 driver
import (
"bufio"
"context"
"crypto/tls"
"database/sql"
"database/sql/driver"
"errors"
"flag"
"fmt"
"io"
"log/slog"
"net"
"regexp"
"runtime/pprof"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/SAP/go-hdb/driver/dial"
p "github.com/SAP/go-hdb/driver/internal/protocol"
"github.com/SAP/go-hdb/driver/internal/protocol/auth"
"github.com/SAP/go-hdb/driver/internal/protocol/encoding"
hdbreflect "github.com/SAP/go-hdb/driver/internal/reflect"
)
// ErrUnsupportedIsolationLevel is the error raised if a transaction is started with a not supported isolation level.
var ErrUnsupportedIsolationLevel = errors.New("unsupported isolation level")
// ErrNestedTransaction is the error raised if a transaction is created within a transaction as this is not supported by hdb.
var ErrNestedTransaction = errors.New("nested transactions are not supported")
// ErrNestedQuery is the error raised if a new sql statement is sent to the database server before the resultset
// processing of a previous sql query statement is finalized.
// Currently this only can happen if connections are used concurrently and if stream enabled fields (LOBs) are part
// of the resultset.
// This error can be avoided in whether using a transaction or a dedicated connection (sql.Tx or sql.Conn).
var ErrNestedQuery = errors.New("nested sql queries are not supported")
// queries.
const (
dummyQuery = "select 1 from dummy"
setIsolationLevelReadCommitted = "set transaction isolation level read committed"
setIsolationLevelRepeatableRead = "set transaction isolation level repeatable read"
setIsolationLevelSerializable = "set transaction isolation level serializable"
setAccessModeReadOnly = "set transaction read only"
setAccessModeReadWrite = "set transaction read write"
setDefaultSchema = "set schema"
)
var (
// register as var to execute even before init() funcs are called.
_ = p.RegisterScanType(p.DtBytes, hdbreflect.TypeFor[[]byte](), hdbreflect.TypeFor[NullBytes]())
_ = p.RegisterScanType(p.DtDecimal, hdbreflect.TypeFor[Decimal](), hdbreflect.TypeFor[NullDecimal]())
_ = p.RegisterScanType(p.DtLob, hdbreflect.TypeFor[Lob](), hdbreflect.TypeFor[NullLob]())
)
var (
cpuProfile = false
)
// dbConn wraps the database tcp connection. It sets timeouts and handles driver ErrBadConn behavior.
type dbConn struct {
metrics *metrics
conn net.Conn
timeout time.Duration
logger *slog.Logger
lastRead time.Time
lastWrite time.Time
}
func (c *dbConn) deadline() (deadline time.Time) {
if c.timeout == 0 {
return
}
return time.Now().Add(c.timeout)
}
func (c *dbConn) close() error { return c.conn.Close() }
// Read implements the io.Reader interface.
func (c *dbConn) Read(b []byte) (int, error) {
// set timeout
if err := c.conn.SetReadDeadline(c.deadline()); err != nil {
return 0, fmt.Errorf("%w: %w", driver.ErrBadConn, err)
}
c.lastRead = time.Now()
n, err := c.conn.Read(b)
c.metrics.msgCh <- timeMsg{idx: timeRead, d: time.Since(c.lastRead)}
c.metrics.msgCh <- counterMsg{idx: counterBytesRead, v: uint64(n)}
if err != nil {
c.logger.LogAttrs(context.Background(), slog.LevelError, "DB conn read error", slog.String("error", err.Error()), slog.String("local address", c.conn.LocalAddr().String()), slog.String("remote address", c.conn.RemoteAddr().String()))
// wrap error in driver.ErrBadConn
return n, fmt.Errorf("%w: %w", driver.ErrBadConn, err)
}
return n, nil
}
// Write implements the io.Writer interface.
func (c *dbConn) Write(b []byte) (int, error) {
// set timeout
if err := c.conn.SetWriteDeadline(c.deadline()); err != nil {
return 0, fmt.Errorf("%w: %w", driver.ErrBadConn, err)
}
c.lastWrite = time.Now()
n, err := c.conn.Write(b)
c.metrics.msgCh <- timeMsg{idx: timeWrite, d: time.Since(c.lastWrite)}
c.metrics.msgCh <- counterMsg{idx: counterBytesWritten, v: uint64(n)}
if err != nil {
c.logger.LogAttrs(context.Background(), slog.LevelError, "DB conn write error", slog.String("error", err.Error()), slog.String("local address", c.conn.LocalAddr().String()), slog.String("remote address", c.conn.RemoteAddr().String()))
// wrap error in driver.ErrBadConn
return n, fmt.Errorf("%w: %w", driver.ErrBadConn, err)
}
return n, nil
}
type profileDBConn struct {
*dbConn
}
func (c *profileDBConn) Read(b []byte) (n int, err error) {
pprof.Do(context.Background(), pprof.Labels("db", "read"), func(ctx context.Context) {
n, err = c.dbConn.Read(b)
})
return
}
func (c *profileDBConn) Write(b []byte) (n int, err error) {
pprof.Do(context.Background(), pprof.Labels("db", "write"), func(ctx context.Context) {
n, err = c.dbConn.Write(b)
})
return
}
// check if conn implements all required interfaces.
var (
_ driver.Conn = (*conn)(nil)
_ driver.ConnPrepareContext = (*conn)(nil)
_ driver.Pinger = (*conn)(nil)
_ driver.ConnBeginTx = (*conn)(nil)
_ driver.ExecerContext = (*conn)(nil)
_ driver.QueryerContext = (*conn)(nil)
_ driver.NamedValueChecker = (*conn)(nil)
_ driver.SessionResetter = (*conn)(nil)
_ driver.Validator = (*conn)(nil)
_ Conn = (*conn)(nil) // go-hdb enhancements
)
// connHook is a hook for testing.
var connHook func(c *conn, op int)
// connection hook operations.
const (
choNone = iota
choStmtExec
)
var errCancelled = fmt.Errorf("%w: %w", driver.ErrBadConn, errors.New("db call cancelled"))
// Conn enhances a connection with go-hdb specific connection functions.
type Conn interface {
HDBVersion() *Version
DatabaseName() string
DBConnectInfo(ctx context.Context, databaseName string) (*DBConnectInfo, error)
}
var stdConnTracker = &connTracker{}
type connTracker struct {
mu sync.Mutex
_callDB *sql.DB
numConn int64
}
func (t *connTracker) add() { t.mu.Lock(); t.numConn++; t.mu.Unlock() }
func (t *connTracker) remove() {
t.mu.Lock()
defer t.mu.Unlock()
t.numConn--
if t.numConn > 0 {
return
}
t.numConn = 0
if t._callDB != nil {
t._callDB.Close()
t._callDB = nil
}
}
func (t *connTracker) callDB() *sql.DB {
t.mu.Lock()
defer t.mu.Unlock()
if t._callDB == nil {
t._callDB = sql.OpenDB(new(callConnector))
}
return t._callDB
}
// Conn is the implementation of the database/sql/driver Conn interface.
type conn struct {
attrs *connAttrs
metrics *metrics
sqlTrace bool
logger *slog.Logger
dbConn *dbConn
wg sync.WaitGroup // wait for concurrent db calls when closing connections
inTx bool // in transaction
lastError error // last error
sessionID int64
serverOptions *p.ConnectOptions
hdbVersion *Version
dec *encoding.Decoder
pr *p.Reader
pw *p.Writer
}
// isAuthError returns true in case of X509 certificate validation errrors or hdb authentication errors, else otherwise.
func isAuthError(err error) bool {
var certValidationError *auth.CertValidationError
if errors.As(err, &certValidationError) {
return true
}
var hdbErrors *p.HdbErrors
if !errors.As(err, &hdbErrors) {
return false
}
return hdbErrors.Code() == p.HdbErrAuthenticationFailed
}
func connect(ctx context.Context, host string, metrics *metrics, connAttrs *connAttrs, authAttrs *authAttrs) (driver.Conn, error) {
// can we connect via cookie?
if auth := authAttrs.cookieAuth(); auth != nil {
conn, err := newSession(ctx, host, metrics, connAttrs, auth)
if err == nil {
return conn, nil
}
if !isAuthError(err) {
return nil, err
}
authAttrs.invalidateCookie() // cookie auth was not successful - do not try again with the same data
}
lastVersion := authAttrs.version.Load()
for {
authHnd := authAttrs.authHnd()
conn, err := newSession(ctx, host, metrics, connAttrs, authHnd)
if err == nil {
if method, ok := authHnd.Selected().(auth.CookieGetter); ok {
authAttrs.setCookie(method.Cookie())
}
return conn, nil
}
if !isAuthError(err) {
return nil, err
}
if err := authAttrs.refresh(); err != nil {
return nil, err
}
version := authAttrs.version.Load()
if version == lastVersion { // no connection retry in case no new version available
return nil, err
}
lastVersion = version
}
}
var (
protTrace atomic.Bool
sqlTrace atomic.Bool
)
func setTrace(b *atomic.Bool, s string) error {
v, err := strconv.ParseBool(s)
if err == nil {
b.Store(v)
}
return err
}
func init() {
flag.BoolFunc("hdb.protTrace", "enabling hdb protocol trace", func(s string) error { return setTrace(&protTrace, s) })
flag.BoolFunc("hdb.sqlTrace", "enabling hdb sql trace", func(s string) error { return setTrace(&sqlTrace, s) })
}
// SQLTrace returns true if sql tracing output is active, false otherwise.
func SQLTrace() bool { return sqlTrace.Load() }
// SetSQLTrace sets sql tracing output active or inactive.
func SetSQLTrace(on bool) { sqlTrace.Store(on) }
// unique connection number.
var connNo atomic.Uint64
func bufferedReaderWriter(dbConn *dbConn, bufferSize int) (*bufio.Reader, *bufio.Writer) {
if cpuProfile {
profileDBConn := &profileDBConn{dbConn: dbConn}
return bufio.NewReaderSize(profileDBConn, bufferSize), bufio.NewWriterSize(profileDBConn, bufferSize)
}
return bufio.NewReaderSize(dbConn, bufferSize), bufio.NewWriterSize(dbConn, bufferSize)
}
func newConn(ctx context.Context, host string, metrics *metrics, attrs *connAttrs) (*conn, error) {
netConn, err := attrs._dialer.DialContext(ctx, host, dial.DialerOptions{Timeout: attrs._timeout, TCPKeepAlive: attrs._tcpKeepAlive})
if err != nil {
return nil, err
}
metrics.lazyInit()
// is TLS connection requested?
if attrs._tlsConfig != nil {
netConn = tls.Client(netConn, attrs._tlsConfig)
}
logger := attrs._logger.With(slog.Uint64("conn", connNo.Add(1)))
protTrace := protTrace.Load()
dbConn := &dbConn{metrics: metrics, conn: netConn, timeout: attrs._timeout, logger: logger}
reader, writer := bufferedReaderWriter(dbConn, attrs._bufferSize)
enc := encoding.NewEncoder(writer, attrs._cesu8Encoder)
dec := encoding.NewDecoder(reader, attrs._cesu8Decoder)
c := &conn{attrs: attrs, metrics: metrics, dbConn: dbConn, sqlTrace: sqlTrace.Load(), logger: logger, dec: dec, sessionID: defaultSessionID}
c.pw = p.NewWriter(writer, enc, protTrace, logger, attrs._cesu8Encoder, attrs._sessionVariables) // write upstream
c.pr = p.NewDBReader(dec, c.readLob, protTrace, logger, attrs._lobChunkSize) // read downstream
if err := c.pw.WriteProlog(ctx); err != nil {
dbConn.close()
return nil, err
}
if err := c.pr.ReadProlog(ctx); err != nil {
dbConn.close()
return nil, err
}
stdConnTracker.add()
c.metrics.msgCh <- gaugeMsg{idx: gaugeConn, v: 1} // increment open connections.
return c, nil
}
func fetchRedirectHost(ctx context.Context, host, databaseName string, metrics *metrics, attrs *connAttrs) (string, error) {
c, err := newConn(ctx, host, metrics, attrs)
if err != nil {
return "", err
}
defer c.Close()
dbi, err := c.dbConnectInfo(ctx, databaseName)
if err != nil {
return "", err
}
if dbi.IsConnected { // if databaseName == "SYSTEMDB" and isConnected == true host and port are initial
return host, nil
}
return net.JoinHostPort(dbi.Host, strconv.Itoa(dbi.Port)), nil
}
func newSession(ctx context.Context, host string, metrics *metrics, attrs *connAttrs, authHnd *p.AuthHnd) (driver.Conn, error) {
c, err := newConn(ctx, host, metrics, attrs)
if err != nil {
return nil, err
}
if err := c.initSession(ctx, attrs, authHnd); err != nil {
c.Close()
return nil, err
}
return c, nil
}
func (c *conn) initSession(ctx context.Context, attrs *connAttrs, authHnd *p.AuthHnd) (err error) {
if c.sessionID, c.serverOptions, err = c.authenticate(ctx, authHnd, attrs); err != nil {
return err
}
if c.sessionID <= 0 {
return fmt.Errorf("invalid session id %d", c.sessionID)
}
c.hdbVersion = parseVersion(c.versionString())
c.dec.SetAlphanumDfv1(c.serverOptions.DataFormatVersion2OrZero() == p.DfvLevel1)
c.dec.SetEmptyDateAsNull(attrs._emptyDateAsNull)
if attrs._defaultSchema != "" {
if _, err := c.ExecContext(ctx, strings.Join([]string{setDefaultSchema, Identifier(attrs._defaultSchema).String()}, " "), nil); err != nil {
return err
}
}
return nil
}
func (c *conn) versionString() (version string) { return c.serverOptions.FullVersionOrZero() }
// ResetSession implements the driver.SessionResetter interface.
func (c *conn) ResetSession(ctx context.Context) error {
if c.isBad() {
return driver.ErrBadConn
}
c.lastError = nil
if c.attrs._pingInterval == 0 || c.dbConn.lastRead.IsZero() || time.Since(c.dbConn.lastRead) < c.attrs._pingInterval {
return nil
}
if _, err := c.queryDirect(ctx, dummyQuery, !c.inTx); err != nil {
return driver.ErrBadConn
}
return nil
}
func (c *conn) isBad() bool { return errors.Is(c.lastError, driver.ErrBadConn) }
// IsValid implements the driver.Validator interface.
func (c *conn) IsValid() bool { return !c.isBad() }
// Ping implements the driver.Pinger interface.
func (c *conn) Ping(ctx context.Context) error {
if c.sqlTrace {
defer c.logSQLTrace(ctx, time.Now(), dummyQuery, nil)
}
done := make(chan struct{})
var err error
c.wg.Add(1)
go func() {
defer c.wg.Done()
_, err = c.queryDirect(ctx, dummyQuery, !c.inTx)
close(done)
}()
select {
case <-ctx.Done():
c.lastError = errCancelled
return ctx.Err()
case <-done:
c.lastError = err
return err
}
}
// PrepareContext implements the driver.ConnPrepareContext interface.
func (c *conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
if c.sqlTrace {
defer c.logSQLTrace(ctx, time.Now(), query, nil)
}
done := make(chan struct{})
var stmt driver.Stmt
var err error
c.wg.Add(1)
go func() {
defer c.wg.Done()
var pr *prepareResult
if pr, err = c.prepare(ctx, query); err == nil {
stmt = newStmt(c, query, pr)
if stmtMetadata, ok := ctx.Value(stmtMetadataCtxKey).(*StmtMetadata); ok {
*stmtMetadata = pr
}
}
close(done)
}()
select {
case <-ctx.Done():
c.lastError = errCancelled
return nil, ctx.Err()
case <-done:
c.lastError = err
return stmt, err
}
}
// Close implements the driver.Conn interface.
func (c *conn) Close() error {
c.wg.Wait() // wait until concurrent db calls are finalized
c.metrics.msgCh <- gaugeMsg{idx: gaugeConn, v: -1} // decrement open connections.
// do not disconnect if isBad or invalid sessionID
if !c.isBad() && c.sessionID != defaultSessionID {
c.disconnect(context.Background()) //nolint:errcheck
}
err := c.dbConn.close()
stdConnTracker.remove()
return err
}
// BeginTx implements the driver.ConnBeginTx interface.
func (c *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
if c.inTx {
return nil, ErrNestedTransaction
}
var isolationLevelQuery string
switch sql.IsolationLevel(opts.Isolation) {
case sql.LevelDefault, sql.LevelReadCommitted:
isolationLevelQuery = setIsolationLevelReadCommitted
case sql.LevelRepeatableRead:
isolationLevelQuery = setIsolationLevelRepeatableRead
case sql.LevelSerializable:
isolationLevelQuery = setIsolationLevelSerializable
default:
return nil, ErrUnsupportedIsolationLevel
}
done := make(chan struct{})
var tx driver.Tx
var err error
c.wg.Add(1)
go func() {
defer c.wg.Done()
// set isolation level
if _, err = c.execDirect(ctx, isolationLevelQuery, !c.inTx); err != nil {
goto done
}
// set access mode
if opts.ReadOnly {
_, err = c.execDirect(ctx, setAccessModeReadOnly, !c.inTx)
} else {
_, err = c.execDirect(ctx, setAccessModeReadWrite, !c.inTx)
}
if err != nil {
goto done
}
c.inTx = true
tx = newTx(c)
done:
close(done)
}()
select {
case <-ctx.Done():
c.lastError = errCancelled
return nil, ctx.Err()
case <-done:
c.lastError = err
return tx, err
}
}
var callStmt = regexp.MustCompile(`(?i)^\s*call\s+.*`) // sql statement beginning with call
// QueryContext implements the driver.QueryerContext interface.
func (c *conn) QueryContext(ctx context.Context, query string, nvargs []driver.NamedValue) (driver.Rows, error) {
if callStmt.MatchString(query) {
return nil, fmt.Errorf("invalid procedure call %s - please use Exec instead", query)
}
if len(nvargs) != 0 {
return nil, driver.ErrSkip // fast path not possible (prepare needed)
}
if c.sqlTrace {
defer c.logSQLTrace(ctx, time.Now(), query, nvargs)
}
done := make(chan struct{})
var rows driver.Rows
var err error
c.wg.Add(1)
go func() {
defer c.wg.Done()
rows, err = c.queryDirect(ctx, query, !c.inTx)
close(done)
}()
select {
case <-ctx.Done():
c.lastError = errCancelled
return nil, ctx.Err()
case <-done:
c.lastError = err
return rows, err
}
}
// ExecContext implements the driver.ExecerContext interface.
func (c *conn) ExecContext(ctx context.Context, query string, nvargs []driver.NamedValue) (driver.Result, error) {
if len(nvargs) != 0 {
return nil, driver.ErrSkip // fast path not possible (prepare needed)
}
if c.sqlTrace {
defer c.logSQLTrace(ctx, time.Now(), query, nvargs)
}
done := make(chan struct{})
var result driver.Result
var err error
c.wg.Add(1)
go func() {
defer c.wg.Done()
// handle procesure call without parameters here as well
result, err = c.execDirect(ctx, query, !c.inTx)
close(done)
}()
select {
case <-ctx.Done():
c.lastError = errCancelled
return nil, ctx.Err()
case <-done:
c.lastError = err
return result, err
}
}
// CheckNamedValue implements the NamedValueChecker interface.
func (c *conn) CheckNamedValue(nv *driver.NamedValue) error {
// - called by sql driver for ExecContext and QueryContext
// - no check needs to be performed as ExecContext and QueryContext provided
// with parameters will force the 'prepare way' (driver.ErrSkip)
// - Anyway, CheckNamedValue must be implemented to avoid default sql driver checks
// which would fail for custom arg types like Lob
return nil
}
// Conn Raw access methods
// HDBVersion implements the Conn interface.
func (c *conn) HDBVersion() *Version { return c.hdbVersion }
// DatabaseName implements the Conn interface.
func (c *conn) DatabaseName() string { return c.serverOptions.DatabaseNameOrZero() }
// DBConnectInfo implements the Conn interface.
func (c *conn) DBConnectInfo(ctx context.Context, databaseName string) (*DBConnectInfo, error) {
done := make(chan struct{})
var ci *DBConnectInfo
var err error
c.wg.Add(1)
go func() {
defer c.wg.Done()
ci, err = c.dbConnectInfo(ctx, databaseName)
close(done)
}()
select {
case <-ctx.Done():
c.lastError = errCancelled
return nil, ctx.Err()
case <-done:
c.lastError = err
return ci, err
}
}
func (c *conn) logSQLTrace(ctx context.Context, start time.Time, query string, nvargs []driver.NamedValue) {
const maxArg = 5 // limit the number of arguments to 5
l := len(nvargs)
if l == 0 {
c.logger.LogAttrs(ctx, slog.LevelInfo, "SQL", slog.String("query", query), slog.Int64("ms", time.Since(start).Milliseconds()))
return
}
var attrs []slog.Attr
for i := 0; i < min(l, maxArg); i++ {
name := nvargs[i].Name
if name == "" {
name = strconv.Itoa(nvargs[i].Ordinal)
}
attrs = append(attrs, slog.String(name, fmt.Sprintf("%v", nvargs[i].Value)))
}
if l > maxArg {
attrs = append(attrs, slog.Int("numArgSkip", l-maxArg))
}
c.logger.LogAttrs(ctx, slog.LevelInfo, "SQL", slog.String("query", query), slog.Int64("ms", time.Since(start).Milliseconds()), slog.Any("arg", slog.GroupValue(attrs...)))
}
func (c *conn) addTimeValue(start time.Time, k int) {
c.metrics.msgCh <- timeMsg{idx: k, d: time.Since(start)}
}
func (c *conn) addSQLTimeValue(start time.Time, k int) {
c.metrics.msgCh <- sqlTimeMsg{idx: k, d: time.Since(start)}
}
// transaction.
// check if tx implements all required interfaces.
var (
_ driver.Tx = (*tx)(nil)
)
type tx struct {
conn *conn
closed bool
}
func newTx(conn *conn) *tx {
conn.metrics.msgCh <- gaugeMsg{idx: gaugeTx, v: 1} // increment number of transactions.
return &tx{conn: conn}
}
func (t *tx) Commit() error { return t.close(false) }
func (t *tx) Rollback() error { return t.close(true) }
func (t *tx) close(rollback bool) error {
c := t.conn
c.metrics.msgCh <- gaugeMsg{idx: gaugeTx, v: -1} // decrement number of transactions.
if c.isBad() {
return driver.ErrBadConn
}
if t.closed {
return nil
}
t.closed = true
c.inTx = false
if rollback {
return c.rollback(context.Background())
}
return c.commit(context.Background())
}
const defaultSessionID = -1
func (c *conn) dbConnectInfo(ctx context.Context, databaseName string) (*DBConnectInfo, error) {
ci := &p.DBConnectInfo{}
ci.SetDatabaseName(databaseName)
if err := c.pw.Write(ctx, c.sessionID, p.MtDBConnectInfo, false, ci); err != nil {
return nil, err
}
if _, err := c.pr.IterateParts(ctx, 0, func(kind p.PartKind, attrs p.PartAttributes, readFn func(part p.Part)) {
if kind == p.PkDBConnectInfo {
readFn(ci)
}
}); err != nil {
return nil, err
}
return &DBConnectInfo{
DatabaseName: databaseName,
Host: ci.HostOrZero(),
Port: ci.PortOrZero(),
IsConnected: ci.IsConnectedOrZero(),
}, nil
}
func (c *conn) authenticate(ctx context.Context, authHnd *p.AuthHnd, attrs *connAttrs) (int64, *p.ConnectOptions, error) {
defer c.addTimeValue(time.Now(), timeAuth)
// client context
clientContext := &p.ClientContext{}
clientContext.SetVersion(DriverVersion)
clientContext.SetType(clientType)
clientContext.SetApplicationProgram(attrs._applicationName)
initRequest, err := authHnd.InitRequest()
if err != nil {
return 0, nil, err
}
if err := c.pw.Write(ctx, c.sessionID, p.MtAuthenticate, false, clientContext, initRequest); err != nil {
return 0, nil, err
}
initReply, err := authHnd.InitReply()
if err != nil {
return 0, nil, err
}
if _, err := c.pr.IterateParts(ctx, 0, func(kind p.PartKind, attrs p.PartAttributes, readFn func(part p.Part)) {
if kind == p.PkAuthentication {
readFn(initReply)
}
}); err != nil {
return 0, nil, err
}
finalRequest, err := authHnd.FinalRequest()
if err != nil {
return 0, nil, err
}
co := &p.ConnectOptions{}
co.SetDataFormatVersion2(attrs._dfv)
co.SetClientDistributionMode(p.CdmOff)
// co.SetClientDistributionMode(p.CdmConnectionStatement)
// co.SetSelectForUpdateSupported(true) // doesn't seem to make a difference
/*
p.CoSplitBatchCommands: true,
p.CoCompleteArrayExecution: true,
*/
if attrs._locale != "" {
co.SetClientLocale(attrs._locale)
}
if err := c.pw.Write(ctx, c.sessionID, p.MtConnect, false, finalRequest, p.ClientID(clientID), co); err != nil {
return 0, nil, err
}
finalReply, err := authHnd.FinalReply()
if err != nil {
return 0, nil, err
}
ti := new(p.TopologyInformation)
if _, err := c.pr.IterateParts(ctx, 0, func(kind p.PartKind, attrs p.PartAttributes, readFn func(part p.Part)) {
switch kind {
case p.PkAuthentication:
readFn(finalReply)
case p.PkConnectOptions:
readFn(co)
case p.PkTopologyInformation:
readFn(ti)
}
}); err != nil {
return 0, nil, err
}
// log.Printf("co: %s", co)
// log.Printf("ti: %s", ti)
return c.pr.SessionID(), co, nil
}
func (c *conn) queryDirect(ctx context.Context, query string, commit bool) (driver.Rows, error) {
defer c.addSQLTimeValue(time.Now(), sqlTimeQuery)
// allow e.g inserts as query -> handle commit like in _execDirect
if err := c.pw.Write(ctx, c.sessionID, p.MtExecuteDirect, commit, p.Command(query)); err != nil {
return nil, err
}
qr := &queryResult{conn: c}
meta := &p.ResultMetadata{}
resSet := &p.Resultset{}
if _, err := c.pr.IterateParts(ctx, 0, func(kind p.PartKind, attrs p.PartAttributes, readFn func(part p.Part)) {
switch kind {
case p.PkResultMetadata:
readFn(meta)
qr.fields = meta.ResultFields
case p.PkResultsetID:
readFn((*p.ResultsetID)(&qr.rsID))
case p.PkResultset:
resSet.ResultFields = qr.fields
readFn(resSet)
qr.fieldValues = resSet.FieldValues
qr.decodeErrors = resSet.DecodeErrors
qr.attrs = attrs
}
}); err != nil {
return nil, err
}
if qr.rsID == 0 { // non select query
return noResult, nil
}
return qr, nil
}
func (c *conn) execDirect(ctx context.Context, query string, commit bool) (driver.Result, error) {
defer c.addSQLTimeValue(time.Now(), sqlTimeExec)
if err := c.pw.Write(ctx, c.sessionID, p.MtExecuteDirect, commit, p.Command(query)); err != nil {
return nil, err
}
numRow, err := c.pr.IterateParts(ctx, 0, nil)
if err != nil {
return nil, err
}
if c.pr.FunctionCode() == p.FcDDL {
return driver.ResultNoRows, nil
}
return driver.RowsAffected(numRow), nil
}
func (c *conn) prepare(ctx context.Context, query string) (*prepareResult, error) {
defer c.addSQLTimeValue(time.Now(), sqlTimePrepare)
if err := c.pw.Write(ctx, c.sessionID, p.MtPrepare, false, p.Command(query)); err != nil {
return nil, err
}
pr := &prepareResult{}
resMeta := &p.ResultMetadata{}
prmMeta := &p.ParameterMetadata{}
if _, err := c.pr.IterateParts(ctx, 0, func(kind p.PartKind, attrs p.PartAttributes, readFn func(part p.Part)) {
switch kind {
case p.PkStatementID:
readFn((*p.StatementID)(&pr.stmtID))
case p.PkResultMetadata:
readFn(resMeta)
pr.resultFields = resMeta.ResultFields
case p.PkParameterMetadata:
readFn(prmMeta)
pr.parameterFields = prmMeta.ParameterFields
}
}); err != nil {
return nil, err
}
pr.fc = c.pr.FunctionCode()
return pr, nil
}
func (c *conn) query(ctx context.Context, pr *prepareResult, nvargs []driver.NamedValue, commit bool) (driver.Rows, error) {
defer c.addSQLTimeValue(time.Now(), sqlTimeQuery)
// allow e.g inserts as query -> handle commit like in exec
if err := convertQueryArgs(pr.parameterFields, nvargs, c.attrs._cesu8Encoder(), c.attrs._lobChunkSize); err != nil {
return nil, err
}
inputParameters, err := p.NewInputParameters(pr.parameterFields, nvargs)
if err != nil {
return nil, err
}
if err := c.pw.Write(ctx, c.sessionID, p.MtExecute, commit, p.StatementID(pr.stmtID), inputParameters); err != nil {
return nil, err
}
qr := &queryResult{conn: c, fields: pr.resultFields}
resSet := &p.Resultset{}
if _, err := c.pr.IterateParts(ctx, 0, func(kind p.PartKind, attrs p.PartAttributes, readFn func(part p.Part)) {
switch kind {
case p.PkResultsetID:
readFn((*p.ResultsetID)(&qr.rsID))
case p.PkResultset:
resSet.ResultFields = qr.fields
readFn(resSet)
qr.fieldValues = resSet.FieldValues
qr.decodeErrors = resSet.DecodeErrors
qr.attrs = attrs
}
}); err != nil {
return nil, err
}
if qr.rsID == 0 { // non select query
return noResult, nil
}
return qr, nil
}
func (c *conn) exec(ctx context.Context, pr *prepareResult, nvargs []driver.NamedValue, commit bool, offset int) (driver.Result, error) {
inputParameters, err := p.NewInputParameters(pr.parameterFields, nvargs)
if err != nil {
return nil, err
}
if err := c.pw.Write(ctx, c.sessionID, p.MtExecute, commit, p.StatementID(pr.stmtID), inputParameters); err != nil {
return nil, err
}
var ids []p.LocatorID
lobReply := &p.WriteLobReply{}
numRow, err := c.pr.IterateParts(ctx, offset, func(kind p.PartKind, attrs p.PartAttributes, readFn func(part p.Part)) {
if kind == p.PkWriteLobReply {
readFn(lobReply)
ids = lobReply.IDs
}
})
if err != nil {
return nil, err
}
fc := c.pr.FunctionCode()
if len(ids) != 0 {
/*
writeLobParameters:
- chunkReaders
- nil (no callResult, exec does not have output parameters)
*/
/*
write lob data only for the last record as lob streaming is only available for the last one
*/
startLastRec := len(nvargs) - len(pr.parameterFields)
if err := c.writeLobs(ctx, nil, ids, pr.parameterFields, nvargs[startLastRec:]); err != nil {
return nil, err
}
}
if fc == p.FcDDL {
return driver.ResultNoRows, nil
}
return driver.RowsAffected(numRow), nil
}
func (c *conn) execCall(ctx context.Context, outputFields []*p.ParameterField) (*callResult, []p.LocatorID, int64, error) {
cr := &callResult{conn: c, outputFields: outputFields}
var qr *queryResult
var ids []p.LocatorID