-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathtrino.go
2403 lines (2200 loc) · 65.1 KB
/
trino.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 (c) Facebook, Inc. and its affiliates. All Rights Reserved
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This file contains code that was borrowed from prestgo, mainly some
// data type definitions.
//
// See https://github.com/avct/prestgo for copyright information.
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Avocet Systems Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Package trino provides a database/sql driver for Trino.
//
// The driver should be used via the database/sql package:
//
// import "database/sql"
// import _ "github.com/trinodb/trino-go-client/trino"
//
// dsn := "http://user@localhost:8080?catalog=default&schema=test"
// db, err := sql.Open("trino", dsn)
package trino
import (
"context"
"crypto/tls"
"crypto/x509"
"database/sql"
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"net/http"
"net/url"
"os"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode"
"github.com/jcmturner/gokrb5/v8/client"
"github.com/jcmturner/gokrb5/v8/config"
"github.com/jcmturner/gokrb5/v8/keytab"
"github.com/jcmturner/gokrb5/v8/spnego"
)
func init() {
sql.Register("trino", &Driver{})
}
var (
// DefaultQueryTimeout is the default timeout for queries executed without a context.
DefaultQueryTimeout = 60 * time.Second
// DefaultCancelQueryTimeout is the timeout for the request to cancel queries in Trino.
DefaultCancelQueryTimeout = 30 * time.Second
// ErrOperationNotSupported indicates that a database operation is not supported.
ErrOperationNotSupported = errors.New("trino: operation not supported")
// ErrQueryCancelled indicates that a query has been cancelled.
ErrQueryCancelled = errors.New("trino: query cancelled")
// ErrUnsupportedHeader indicates that the server response contains an unsupported header.
ErrUnsupportedHeader = errors.New("trino: server response contains an unsupported header")
// ErrInvalidResponseType indicates that the server returned an invalid type definition.
ErrInvalidResponseType = errors.New("trino: server response contains an invalid type")
// ErrInvalidProgressCallbackHeader indicates that server did not get valid headers for progress callback
ErrInvalidProgressCallbackHeader = errors.New("trino: both " + trinoProgressCallbackParam + " and " + trinoProgressCallbackPeriodParam + " must be set when using progress callback")
)
const (
trinoHeaderPrefix = `X-Trino-`
preparedStatementHeader = trinoHeaderPrefix + "Prepared-Statement"
preparedStatementName = "_trino_go"
trinoUserHeader = trinoHeaderPrefix + `User`
trinoSourceHeader = trinoHeaderPrefix + `Source`
trinoCatalogHeader = trinoHeaderPrefix + `Catalog`
trinoSchemaHeader = trinoHeaderPrefix + `Schema`
trinoSessionHeader = trinoHeaderPrefix + `Session`
trinoSetCatalogHeader = trinoHeaderPrefix + `Set-Catalog`
trinoSetSchemaHeader = trinoHeaderPrefix + `Set-Schema`
trinoSetPathHeader = trinoHeaderPrefix + `Set-Path`
trinoSetSessionHeader = trinoHeaderPrefix + `Set-Session`
trinoClearSessionHeader = trinoHeaderPrefix + `Clear-Session`
trinoSetRoleHeader = trinoHeaderPrefix + `Set-Role`
trinoExtraCredentialHeader = trinoHeaderPrefix + `Extra-Credential`
trinoProgressCallbackParam = trinoHeaderPrefix + `Progress-Callback`
trinoProgressCallbackPeriodParam = trinoHeaderPrefix + `Progress-Callback-Period`
trinoAddedPrepareHeader = trinoHeaderPrefix + `Added-Prepare`
trinoDeallocatedPrepareHeader = trinoHeaderPrefix + `Deallocated-Prepare`
authorizationHeader = "Authorization"
kerberosEnabledConfig = "KerberosEnabled"
kerberosKeytabPathConfig = "KerberosKeytabPath"
kerberosPrincipalConfig = "KerberosPrincipal"
kerberosRealmConfig = "KerberosRealm"
kerberosConfigPathConfig = "KerberosConfigPath"
kerberosRemoteServiceNameConfig = "KerberosRemoteServiceName"
sslCertPathConfig = "SSLCertPath"
sslCertConfig = "SSLCert"
accessTokenConfig = "accessToken"
explicitPrepareConfig = "explicitPrepare"
forwardAuthorizationHeaderConfig = "forwardAuthorizationHeader"
mapKeySeparator = ":"
mapEntrySeparator = ";"
)
var (
responseToRequestHeaderMap = map[string]string{
trinoSetSchemaHeader: trinoSchemaHeader,
trinoSetCatalogHeader: trinoCatalogHeader,
}
unsupportedResponseHeaders = []string{
trinoSetPathHeader,
trinoSetRoleHeader,
}
)
type Driver struct{}
func (d *Driver) Open(name string) (driver.Conn, error) {
return newConn(name)
}
var _ driver.Driver = &Driver{}
// Config is a configuration that can be encoded to a DSN string.
type Config struct {
ServerURI string // URI of the Trino server, e.g. http://user@localhost:8080
Source string // Source of the connection (optional)
Catalog string // Catalog (optional)
Schema string // Schema (optional)
SessionProperties map[string]string // Session properties (optional)
ExtraCredentials map[string]string // Extra credentials (optional)
CustomClientName string // Custom client name (optional)
KerberosEnabled string // KerberosEnabled (optional, default is false)
KerberosKeytabPath string // Kerberos Keytab Path (optional)
KerberosPrincipal string // Kerberos Principal used to authenticate to KDC (optional)
KerberosRemoteServiceName string // Trino coordinator Kerberos service name (optional)
KerberosRealm string // The Kerberos Realm (optional)
KerberosConfigPath string // The krb5 config path (optional)
SSLCertPath string // The SSL cert path for TLS verification (optional)
SSLCert string // The SSL cert for TLS verification (optional)
AccessToken string // An access token (JWT) for authentication (optional)
ForwardAuthorizationHeader bool // Allow forwarding the `accessToken` named query parameter in the authorization header, overwriting the `AccessToken` option, if set (optional)
}
// FormatDSN returns a DSN string from the configuration.
func (c *Config) FormatDSN() (string, error) {
serverURL, err := url.Parse(c.ServerURI)
if err != nil {
return "", err
}
var sessionkv []string
if c.SessionProperties != nil {
for k, v := range c.SessionProperties {
sessionkv = append(sessionkv, k+mapKeySeparator+v)
}
}
var credkv []string
if c.ExtraCredentials != nil {
for k, v := range c.ExtraCredentials {
credkv = append(credkv, k+mapKeySeparator+v)
}
}
source := c.Source
if source == "" {
source = "trino-go-client"
}
query := make(url.Values)
query.Add("source", source)
if c.ForwardAuthorizationHeader {
query.Add(forwardAuthorizationHeaderConfig, "true")
}
KerberosEnabled, _ := strconv.ParseBool(c.KerberosEnabled)
isSSL := serverURL.Scheme == "https"
if c.CustomClientName != "" {
if c.SSLCert != "" || c.SSLCertPath != "" {
return "", fmt.Errorf("trino: client configuration error, a custom client cannot be specific together with a custom SSL certificate")
}
}
if c.SSLCertPath != "" {
if !isSSL {
return "", fmt.Errorf("trino: client configuration error, SSL must be enabled to specify a custom SSL certificate file")
}
if c.SSLCert != "" {
return "", fmt.Errorf("trino: client configuration error, a custom SSL certificate file cannot be specified together with a certificate string")
}
query.Add(sslCertPathConfig, c.SSLCertPath)
}
if c.SSLCert != "" {
if !isSSL {
return "", fmt.Errorf("trino: client configuration error, SSL must be enabled to specify a custom SSL certificate")
}
if c.SSLCertPath != "" {
return "", fmt.Errorf("trino: client configuration error, a custom SSL certificate string cannot be specified together with a certificate file")
}
query.Add(sslCertConfig, c.SSLCert)
}
if KerberosEnabled {
if !isSSL {
return "", fmt.Errorf("trino: client configuration error, SSL must be enabled for secure env")
}
query.Add(kerberosEnabledConfig, "true")
query.Add(kerberosKeytabPathConfig, c.KerberosKeytabPath)
query.Add(kerberosPrincipalConfig, c.KerberosPrincipal)
query.Add(kerberosRealmConfig, c.KerberosRealm)
query.Add(kerberosConfigPathConfig, c.KerberosConfigPath)
remoteServiceName := c.KerberosRemoteServiceName
if remoteServiceName == "" {
remoteServiceName = "trino"
}
query.Add(kerberosRemoteServiceNameConfig, remoteServiceName)
}
// ensure consistent order of items
sort.Strings(sessionkv)
sort.Strings(credkv)
for k, v := range map[string]string{
"catalog": c.Catalog,
"schema": c.Schema,
"session_properties": strings.Join(sessionkv, mapEntrySeparator),
"extra_credentials": strings.Join(credkv, mapEntrySeparator),
"custom_client": c.CustomClientName,
accessTokenConfig: c.AccessToken,
} {
if v != "" {
query[k] = []string{v}
}
}
serverURL.RawQuery = query.Encode()
return serverURL.String(), nil
}
// Conn is a Trino connection.
type Conn struct {
baseURL string
auth *url.Userinfo
httpClient http.Client
httpHeaders http.Header
kerberosEnabled bool
kerberosClient *client.Client
kerberosRemoteServiceName string
progressUpdater ProgressUpdater
progressUpdaterPeriod queryProgressCallbackPeriod
useExplicitPrepare bool
forwardAuthorizationHeader bool
}
var (
_ driver.Conn = &Conn{}
_ driver.ConnPrepareContext = &Conn{}
)
func newConn(dsn string) (*Conn, error) {
serverURL, err := url.Parse(dsn)
if err != nil {
return nil, fmt.Errorf("trino: malformed dsn: %w", err)
}
query := serverURL.Query()
kerberosEnabled, _ := strconv.ParseBool(query.Get(kerberosEnabledConfig))
forwardAuthorizationHeader, _ := strconv.ParseBool(query.Get(forwardAuthorizationHeaderConfig))
useExplicitPrepare := true
if query.Get(explicitPrepareConfig) != "" {
useExplicitPrepare, _ = strconv.ParseBool(query.Get(explicitPrepareConfig))
}
var kerberosClient *client.Client
if kerberosEnabled {
kt, err := keytab.Load(query.Get(kerberosKeytabPathConfig))
if err != nil {
return nil, fmt.Errorf("trino: Error loading Keytab: %w", err)
}
conf, err := config.Load(query.Get(kerberosConfigPathConfig))
if err != nil {
return nil, fmt.Errorf("trino: Error loading krb config: %w", err)
}
kerberosClient = client.NewWithKeytab(query.Get(kerberosPrincipalConfig), query.Get(kerberosRealmConfig), kt, conf)
loginErr := kerberosClient.Login()
if loginErr != nil {
return nil, fmt.Errorf("trino: Error login to KDC: %v", loginErr)
}
}
var httpClient = http.DefaultClient
if clientKey := query.Get("custom_client"); clientKey != "" {
httpClient = getCustomClient(clientKey)
if httpClient == nil {
return nil, fmt.Errorf("trino: custom client not registered: %q", clientKey)
}
} else if serverURL.Scheme == "https" {
cert := []byte(query.Get(sslCertConfig))
if certPath := query.Get(sslCertPathConfig); certPath != "" {
cert, err = os.ReadFile(certPath)
if err != nil {
return nil, fmt.Errorf("trino: Error loading SSL Cert File: %w", err)
}
}
if len(cert) != 0 {
certPool := x509.NewCertPool()
certPool.AppendCertsFromPEM(cert)
httpClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: certPool,
},
},
}
}
}
c := &Conn{
baseURL: serverURL.Scheme + "://" + serverURL.Host,
httpClient: *httpClient,
httpHeaders: make(http.Header),
kerberosClient: kerberosClient,
kerberosEnabled: kerberosEnabled,
kerberosRemoteServiceName: query.Get(kerberosRemoteServiceNameConfig),
useExplicitPrepare: useExplicitPrepare,
forwardAuthorizationHeader: forwardAuthorizationHeader,
}
var user string
if serverURL.User != nil {
user = serverURL.User.Username()
pass, _ := serverURL.User.Password()
if pass != "" && serverURL.Scheme == "https" {
c.auth = serverURL.User
}
}
for k, v := range map[string]string{
trinoUserHeader: user,
trinoSourceHeader: query.Get("source"),
trinoCatalogHeader: query.Get("catalog"),
trinoSchemaHeader: query.Get("schema"),
authorizationHeader: getAuthorization(query.Get(accessTokenConfig)),
} {
if v != "" {
c.httpHeaders.Add(k, v)
}
}
for header, param := range map[string]string{
trinoSessionHeader: "session_properties",
trinoExtraCredentialHeader: "extra_credentials",
} {
v := query.Get(param)
if v != "" {
c.httpHeaders[header], err = decodeMapHeader(param, v)
if err != nil {
return c, err
}
}
}
return c, nil
}
func decodeMapHeader(name, input string) ([]string, error) {
result := []string{}
for _, entry := range strings.Split(input, mapEntrySeparator) {
parts := strings.SplitN(entry, mapKeySeparator, 2)
if len(parts) != 2 {
return nil, fmt.Errorf("trino: Malformed %s: %s", name, input)
}
key := parts[0]
value := parts[1]
if len(key) == 0 {
return nil, fmt.Errorf("trino: %s key is empty", name)
}
if len(value) == 0 {
return nil, fmt.Errorf("trino: %s value is empty", name)
}
if !isASCII(key) {
return nil, fmt.Errorf("trino: %s key '%s' contains spaces or is not printable ASCII", name, key)
}
if !isASCII(value) {
// do not log value as it may contain sensitive information
return nil, fmt.Errorf("trino: %s value for key '%s' contains spaces or is not printable ASCII", name, key)
}
result = append(result, key+"="+url.QueryEscape(value))
}
return result, nil
}
func isASCII(s string) bool {
for i := 0; i < len(s); i++ {
if s[i] < '\u0021' || s[i] > '\u007E' {
return false
}
}
return true
}
func getAuthorization(token string) string {
if token == "" {
return ""
}
return fmt.Sprintf("Bearer %s", token)
}
// registry for custom http clients
var customClientRegistry = struct {
sync.RWMutex
Index map[string]http.Client
}{
Index: make(map[string]http.Client),
}
// RegisterCustomClient associates a client to a key in the driver's registry.
//
// Register your custom client in the driver, then refer to it by name in the DSN, on the call to sql.Open:
//
// foobarClient := &http.Client{
// Transport: &http.Transport{
// Proxy: http.ProxyFromEnvironment,
// DialContext: (&net.Dialer{
// Timeout: 30 * time.Second,
// KeepAlive: 30 * time.Second,
// DualStack: true,
// }).DialContext,
// MaxIdleConns: 100,
// IdleConnTimeout: 90 * time.Second,
// TLSHandshakeTimeout: 10 * time.Second,
// ExpectContinueTimeout: 1 * time.Second,
// TLSClientConfig: &tls.Config{
// // your config here...
// },
// },
// }
// trino.RegisterCustomClient("foobar", foobarClient)
// db, err := sql.Open("trino", "https://user@localhost:8080?custom_client=foobar")
func RegisterCustomClient(key string, client *http.Client) error {
if _, err := strconv.ParseBool(key); err == nil {
return fmt.Errorf("trino: custom client key %q is reserved", key)
}
customClientRegistry.Lock()
customClientRegistry.Index[key] = *client
customClientRegistry.Unlock()
return nil
}
// DeregisterCustomClient removes the client associated to the key.
func DeregisterCustomClient(key string) {
customClientRegistry.Lock()
delete(customClientRegistry.Index, key)
customClientRegistry.Unlock()
}
func getCustomClient(key string) *http.Client {
customClientRegistry.RLock()
defer customClientRegistry.RUnlock()
if client, ok := customClientRegistry.Index[key]; ok {
return &client
}
return nil
}
// Begin implements the driver.Conn interface.
func (c *Conn) Begin() (driver.Tx, error) {
return nil, ErrOperationNotSupported
}
// Prepare implements the driver.Conn interface.
func (c *Conn) Prepare(query string) (driver.Stmt, error) {
return nil, driver.ErrSkip
}
// PrepareContext implements the driver.ConnPrepareContext interface.
func (c *Conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
return &driverStmt{conn: c, query: query}, nil
}
// Close implements the driver.Conn interface.
func (c *Conn) Close() error {
return nil
}
func (c *Conn) newRequest(ctx context.Context, method, url string, body io.Reader, hs http.Header) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
return nil, fmt.Errorf("trino: %w", err)
}
if c.kerberosEnabled {
remoteServiceName := "trino"
if c.kerberosRemoteServiceName != "" {
remoteServiceName = c.kerberosRemoteServiceName
}
err = spnego.SetSPNEGOHeader(c.kerberosClient, req, remoteServiceName+"/"+req.URL.Hostname())
if err != nil {
return nil, fmt.Errorf("error setting client SPNEGO header: %w", err)
}
}
for k, v := range c.httpHeaders {
req.Header[k] = v
}
for k, v := range hs {
req.Header[k] = v
}
if c.auth != nil {
pass, _ := c.auth.Password()
req.SetBasicAuth(c.auth.Username(), pass)
}
return req, nil
}
func (c *Conn) roundTrip(ctx context.Context, req *http.Request) (*http.Response, error) {
delay := 100 * time.Millisecond
const maxDelayBetweenRequests = float64(15 * time.Second)
timer := time.NewTimer(0)
defer timer.Stop()
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-timer.C:
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, &ErrQueryFailed{Reason: err}
}
switch resp.StatusCode {
case http.StatusOK:
for src, dst := range responseToRequestHeaderMap {
if v := resp.Header.Get(src); v != "" {
c.httpHeaders.Set(dst, v)
}
}
if v := resp.Header.Get(trinoAddedPrepareHeader); v != "" {
c.httpHeaders.Add(preparedStatementHeader, v)
}
if v := resp.Header.Get(trinoDeallocatedPrepareHeader); v != "" {
values := c.httpHeaders.Values(preparedStatementHeader)
c.httpHeaders.Del(preparedStatementHeader)
for _, v2 := range values {
if !strings.HasPrefix(v2, v+"=") {
c.httpHeaders.Add(preparedStatementHeader, v2)
}
}
}
if v := resp.Header.Get(trinoSetSessionHeader); v != "" {
c.httpHeaders.Add(trinoSessionHeader, v)
}
if v := resp.Header.Get(trinoClearSessionHeader); v != "" {
values := c.httpHeaders.Values(trinoSessionHeader)
c.httpHeaders.Del(trinoSessionHeader)
for _, v2 := range values {
if !strings.HasPrefix(v2, v+"=") {
c.httpHeaders.Add(trinoSessionHeader, v2)
}
}
}
for _, name := range unsupportedResponseHeaders {
if v := resp.Header.Get(name); v != "" {
return nil, ErrUnsupportedHeader
}
}
return resp, nil
case http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:
resp.Body.Close()
timer.Reset(delay)
delay = time.Duration(math.Min(
float64(delay)*math.Phi,
maxDelayBetweenRequests,
))
continue
default:
return nil, newErrQueryFailedFromResponse(resp)
}
}
}
}
// ErrQueryFailed indicates that a query to Trino failed.
type ErrQueryFailed struct {
StatusCode int
Reason error
}
// Error implements the error interface.
func (e *ErrQueryFailed) Error() string {
return fmt.Sprintf("trino: query failed (%d %s): %q",
e.StatusCode, http.StatusText(e.StatusCode), e.Reason)
}
// Unwrap implements the unwrap interface.
func (e *ErrQueryFailed) Unwrap() error {
return e.Reason
}
func newErrQueryFailedFromResponse(resp *http.Response) *ErrQueryFailed {
const maxBytes = 8 * 1024
defer resp.Body.Close()
qf := &ErrQueryFailed{StatusCode: resp.StatusCode}
b, err := io.ReadAll(io.LimitReader(resp.Body, maxBytes))
if err != nil {
qf.Reason = err
return qf
}
reason := string(b)
if resp.ContentLength > maxBytes {
reason += "..."
}
qf.Reason = errors.New(reason)
return qf
}
type driverStmt struct {
conn *Conn
query string
user string
nextURIs chan string
httpResponses chan *http.Response
queryResponses chan queryResponse
statsCh chan QueryProgressInfo
errors chan error
doneCh chan struct{}
}
var (
_ driver.Stmt = &driverStmt{}
_ driver.StmtQueryContext = &driverStmt{}
_ driver.StmtExecContext = &driverStmt{}
_ driver.NamedValueChecker = &driverStmt{}
)
// Close closes statement just before releasing connection
func (st *driverStmt) Close() error {
if st.doneCh == nil {
return nil
}
close(st.doneCh)
if st.statsCh != nil {
<-st.statsCh
st.statsCh = nil
}
go func() {
// drain errors chan to allow goroutines to write to it
for range st.errors {
}
}()
for range st.queryResponses {
}
for range st.httpResponses {
}
close(st.nextURIs)
close(st.errors)
st.doneCh = nil
return nil
}
func (st *driverStmt) NumInput() int {
return -1
}
func (st *driverStmt) Exec(args []driver.Value) (driver.Result, error) {
return nil, driver.ErrSkip
}
func (st *driverStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) {
sr, err := st.exec(ctx, args)
if err != nil {
return nil, err
}
rows := &driverRows{
ctx: ctx,
stmt: st,
queryID: sr.ID,
nextURI: sr.NextURI,
rowsAffected: sr.UpdateCount,
statsCh: st.statsCh,
doneCh: st.doneCh,
}
// consume all results, if there are any
for err == nil {
err = rows.fetch()
}
if err != nil && err != io.EOF {
return nil, err
}
return rows, nil
}
func (st *driverStmt) CheckNamedValue(arg *driver.NamedValue) error {
switch arg.Value.(type) {
case nil:
return nil
case Numeric, trinoDate, trinoTime, trinoTimeTz, trinoTimestamp, time.Duration:
return nil
default:
{
if reflect.TypeOf(arg.Value).Kind() == reflect.Slice {
return nil
}
if arg.Name == trinoProgressCallbackParam {
return nil
}
if arg.Name == trinoProgressCallbackPeriodParam {
return nil
}
}
}
return driver.ErrSkip
}
type stmtResponse struct {
ID string `json:"id"`
InfoURI string `json:"infoUri"`
NextURI string `json:"nextUri"`
Stats stmtStats `json:"stats"`
Error ErrTrino `json:"error"`
UpdateType string `json:"updateType"`
UpdateCount int64 `json:"updateCount"`
}
type stmtStats struct {
State string `json:"state"`
Scheduled bool `json:"scheduled"`
Nodes int `json:"nodes"`
TotalSplits int `json:"totalSplits"`
QueuesSplits int `json:"queuedSplits"`
RunningSplits int `json:"runningSplits"`
CompletedSplits int `json:"completedSplits"`
UserTimeMillis int `json:"userTimeMillis"`
CPUTimeMillis int64 `json:"cpuTimeMillis"`
WallTimeMillis int64 `json:"wallTimeMillis"`
QueuedTimeMillis int64 `json:"queuedTimeMillis"`
ElapsedTimeMillis int64 `json:"elapsedTimeMillis"`
ProcessedRows int64 `json:"processedRows"`
ProcessedBytes int64 `json:"processedBytes"`
PhysicalInputBytes int64 `json:"physicalInputBytes"`
PhysicalWrittenBytes int64 `json:"physicalWrittenBytes"`
PeakMemoryBytes int64 `json:"peakMemoryBytes"`
SpilledBytes int64 `json:"spilledBytes"`
RootStage stmtStage `json:"rootStage"`
ProgressPercentage jsonFloat64 `json:"progressPercentage"`
RunningPercentage jsonFloat64 `json:"runningPercentage"`
}
type ErrTrino struct {
Message string `json:"message"`
SqlState string `json:"sqlState"`
ErrorCode int `json:"errorCode"`
ErrorName string `json:"errorName"`
ErrorType string `json:"errorType"`
ErrorLocation ErrorLocation `json:"errorLocation"`
FailureInfo FailureInfo `json:"failureInfo"`
}
func (i ErrTrino) Error() string {
return i.ErrorType + ": " + i.Message
}
type ErrorLocation struct {
LineNumber int `json:"lineNumber"`
ColumnNumber int `json:"columnNumber"`
}
type FailureInfo struct {
Type string `json:"type"`
Message string `json:"message"`
Cause *FailureInfo `json:"cause"`
Suppressed []FailureInfo `json:"suppressed"`
Stack []string `json:"stack"`
ErrorInfo ErrorInfo `json:"errorInfo"`
ErrorLocation ErrorLocation `json:"errorLocation"`
}
type ErrorInfo struct {
Code int `json:"code"`
Name string `json:"name"`
Type string `json:"type"`
}
func (i ErrorInfo) Error() string {
return fmt.Sprintf("%s: %s (%d)", i.Type, i.Name, i.Code)
}
type stmtStage struct {
StageID string `json:"stageId"`
State string `json:"state"`
Done bool `json:"done"`
Nodes int `json:"nodes"`
TotalSplits int `json:"totalSplits"`
QueuedSplits int `json:"queuedSplits"`
RunningSplits int `json:"runningSplits"`
CompletedSplits int `json:"completedSplits"`
UserTimeMillis int `json:"userTimeMillis"`
CPUTimeMillis int `json:"cpuTimeMillis"`
WallTimeMillis int `json:"wallTimeMillis"`
ProcessedRows int `json:"processedRows"`
ProcessedBytes int `json:"processedBytes"`
SubStages []stmtStage `json:"subStages"`
}
type jsonFloat64 float64
func (f *jsonFloat64) UnmarshalJSON(data []byte) error {
var v float64
err := json.Unmarshal(data, &v)
if err != nil {
var jsonErr *json.UnmarshalTypeError
if errors.As(err, &jsonErr) {
if f != nil {
*f = 0
}
return nil
}
return err
}
p := (*float64)(f)
*p = v
return nil
}
var _ json.Unmarshaler = new(jsonFloat64)
func (st *driverStmt) Query(args []driver.Value) (driver.Rows, error) {
return nil, driver.ErrSkip
}
func (st *driverStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) {
sr, err := st.exec(ctx, args)
if err != nil {
return nil, err
}
rows := &driverRows{
ctx: ctx,
stmt: st,
queryID: sr.ID,
nextURI: sr.NextURI,
statsCh: st.statsCh,
doneCh: st.doneCh,
}
if err = rows.fetch(); err != nil && err != io.EOF {
return nil, err
}
return rows, nil
}
func (st *driverStmt) exec(ctx context.Context, args []driver.NamedValue) (*stmtResponse, error) {
query := st.query
hs := make(http.Header)
// Ensure the server returns timestamps preserving their precision, without truncating them to timestamp(3).
hs.Add("X-Trino-Client-Capabilities", "PARAMETRIC_DATETIME")
if len(args) > 0 {
var ss []string
for _, arg := range args {
if arg.Name == trinoProgressCallbackParam {
st.conn.progressUpdater = arg.Value.(ProgressUpdater)
continue
}
if arg.Name == trinoProgressCallbackPeriodParam {
st.conn.progressUpdaterPeriod.Period = arg.Value.(time.Duration)
continue
}
if st.conn.forwardAuthorizationHeader && arg.Name == accessTokenConfig {
token := arg.Value.(string)
hs.Add(authorizationHeader, getAuthorization(token))
continue
}
s, err := Serial(arg.Value)
if err != nil {
return nil, err
}
if strings.HasPrefix(arg.Name, trinoHeaderPrefix) {
headerValue := arg.Value.(string)
if arg.Name == trinoUserHeader {
st.user = headerValue
}
hs.Add(arg.Name, headerValue)
} else {
if st.conn.useExplicitPrepare && hs.Get(preparedStatementHeader) == "" {
for _, v := range st.conn.httpHeaders.Values(preparedStatementHeader) {
hs.Add(preparedStatementHeader, v)
}
hs.Add(preparedStatementHeader, preparedStatementName+"="+url.QueryEscape(st.query))
}
ss = append(ss, s)
}
}
if (st.conn.progressUpdater != nil && st.conn.progressUpdaterPeriod.Period == 0) || (st.conn.progressUpdater == nil && st.conn.progressUpdaterPeriod.Period > 0) {
return nil, ErrInvalidProgressCallbackHeader
}
if len(ss) > 0 {
if st.conn.useExplicitPrepare {
query = "EXECUTE " + preparedStatementName + " USING " + strings.Join(ss, ", ")
} else {
query = "EXECUTE IMMEDIATE " + formatStringLiteral(st.query) + " USING " + strings.Join(ss, ", ")
}
}
}
var cancel context.CancelFunc = func() {}
if _, ok := ctx.Deadline(); !ok {
ctx, cancel = context.WithTimeout(ctx, DefaultQueryTimeout)
}
req, err := st.conn.newRequest(ctx, "POST", st.conn.baseURL+"/v1/statement", strings.NewReader(query), hs)
if err != nil {
cancel()
return nil, err
}
resp, err := st.conn.roundTrip(ctx, req)
if err != nil {
cancel()
return nil, err
}
defer resp.Body.Close()
var sr stmtResponse
d := json.NewDecoder(resp.Body)
d.UseNumber()
err = d.Decode(&sr)
if err != nil {
cancel()
return nil, fmt.Errorf("trino: %w", err)
}
st.doneCh = make(chan struct{})
st.nextURIs = make(chan string)
st.httpResponses = make(chan *http.Response)
st.queryResponses = make(chan queryResponse)
st.errors = make(chan error)
go func() {
defer close(st.httpResponses)
for {
select {
case nextURI := <-st.nextURIs:
if nextURI == "" {