-
Notifications
You must be signed in to change notification settings - Fork 57
/
presto.go
1564 lines (1425 loc) · 39 KB
/
presto.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 presto provides a database/sql driver for Facebook's Presto.
//
// The driver should be used via the database/sql package:
//
// import "database/sql"
// import _ "github.com/prestodb/presto-go-client/presto"
//
// dsn := "http://user@localhost:8080?catalog=default&schema=test"
// db, err := sql.Open("presto", dsn)
//
package presto
import (
"context"
"crypto/tls"
"crypto/x509"
"database/sql"
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"sync"
"time"
"unicode"
"gopkg.in/jcmturner/gokrb5.v6/client"
"gopkg.in/jcmturner/gokrb5.v6/config"
"gopkg.in/jcmturner/gokrb5.v6/keytab"
)
func init() {
sql.Register("presto", &sqldriver{})
}
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 presto.
DefaultCancelQueryTimeout = 30 * time.Second
// ErrOperationNotSupported indicates that a database operation is not supported.
ErrOperationNotSupported = errors.New("presto: operation not supported")
// ErrQueryCancelled indicates that a query has been cancelled.
ErrQueryCancelled = errors.New("presto: query cancelled")
)
const (
preparedStatementHeader = "X-Presto-Prepared-Statement"
preparedStatementName = "_presto_go"
prestoUserHeader = "X-Presto-User"
prestoSourceHeader = "X-Presto-Source"
prestoCatalogHeader = "X-Presto-Catalog"
prestoSchemaHeader = "X-Presto-Schema"
prestoSessionHeader = "X-Presto-Session"
KerberosEnabledConfig = "KerberosEnabled"
kerberosKeytabPathConfig = "KerberosKeytabPath"
kerberosPrincipalConfig = "KerberosPrincipal"
kerberosRealmConfig = "KerberosRealm"
kerberosConfigPathConfig = "KerberosConfigPath"
SSLCertPathConfig = "SSLCertPath"
)
type sqldriver struct{}
func (d *sqldriver) Open(name string) (driver.Conn, error) {
return newConn(name)
}
var _ driver.Driver = &sqldriver{}
// Config is a configuration that can be encoded to a DSN string.
type Config struct {
PrestoURI string // URI of the Presto 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)
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)
KerberosRealm string // The Kerberos Realm (optional)
KerberosConfigPath string // The krb5 config path (optional)
SSLCertPath string // The SSL cert path for TLS verification (optional)
}
// FormatDSN returns a DSN string from the configuration.
func (c *Config) FormatDSN() (string, error) {
prestoURL, err := url.Parse(c.PrestoURI)
if err != nil {
return "", err
}
var sessionkv []string
if c.SessionProperties != nil {
for k, v := range c.SessionProperties {
sessionkv = append(sessionkv, k+"="+v)
}
}
source := c.Source
if source == "" {
source = "presto-go-client"
}
query := make(url.Values)
query.Add("source", source)
KerberosEnabled, _ := strconv.ParseBool(c.KerberosEnabled)
isSSL := prestoURL.Scheme == "https"
if isSSL && c.SSLCertPath != "" {
query.Add(SSLCertPathConfig, c.SSLCertPath)
}
if KerberosEnabled {
query.Add(KerberosEnabledConfig, "true")
query.Add(kerberosKeytabPathConfig, c.KerberosKeytabPath)
query.Add(kerberosPrincipalConfig, c.KerberosPrincipal)
query.Add(kerberosRealmConfig, c.KerberosRealm)
query.Add(kerberosConfigPathConfig, c.KerberosConfigPath)
if !isSSL {
return "", fmt.Errorf("presto: client configuration error, SSL must be enabled for secure env")
}
}
for k, v := range map[string]string{
"catalog": c.Catalog,
"schema": c.Schema,
"session_properties": strings.Join(sessionkv, ","),
"custom_client": c.CustomClientName,
} {
if v != "" {
query[k] = []string{v}
}
}
prestoURL.RawQuery = query.Encode()
return prestoURL.String(), nil
}
// Conn is a presto connection.
type Conn struct {
baseURL string
auth *url.Userinfo
httpClient http.Client
httpHeaders http.Header
kerberosClient client.Client
kerberosEnabled bool
}
var (
_ driver.Conn = &Conn{}
_ driver.ConnPrepareContext = &Conn{}
)
func newConn(dsn string) (*Conn, error) {
prestoURL, err := url.Parse(dsn)
if err != nil {
return nil, fmt.Errorf("presto: malformed dsn: %v", err)
}
prestoQuery := prestoURL.Query()
kerberosEnabled, _ := strconv.ParseBool(prestoQuery.Get(KerberosEnabledConfig))
var kerberosClient client.Client
if kerberosEnabled {
kt, err := keytab.Load(prestoQuery.Get(kerberosKeytabPathConfig))
if err != nil {
return nil, fmt.Errorf("presto: Error loading Keytab: %v", err)
}
kerberosClient = client.NewClientWithKeytab(prestoQuery.Get(kerberosPrincipalConfig), prestoQuery.Get(kerberosRealmConfig), kt)
conf, err := config.Load(prestoQuery.Get(kerberosConfigPathConfig))
if err != nil {
return nil, fmt.Errorf("presto: Error loading krb config: %v", err)
}
kerberosClient.WithConfig(conf)
loginErr := kerberosClient.Login()
if loginErr != nil {
return nil, fmt.Errorf("presto: Error login to KDC: %v", loginErr)
}
}
var httpClient = http.DefaultClient
if clientKey := prestoQuery.Get("custom_client"); clientKey != "" {
httpClient = getCustomClient(clientKey)
if httpClient == nil {
return nil, fmt.Errorf("presto: custom client not registered: %q", clientKey)
}
} else if certPath := prestoQuery.Get(SSLCertPathConfig); certPath != "" && prestoURL.Scheme == "https" {
cert, err := ioutil.ReadFile(certPath)
if err != nil {
return nil, fmt.Errorf("presto: Error loading SSL Cert File: %v", err)
}
certPool := x509.NewCertPool()
certPool.AppendCertsFromPEM(cert)
httpClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: certPool,
},
},
}
}
c := &Conn{
baseURL: prestoURL.Scheme + "://" + prestoURL.Host,
httpClient: *httpClient,
httpHeaders: make(http.Header),
kerberosClient: kerberosClient,
kerberosEnabled: kerberosEnabled,
}
var user string
if prestoURL.User != nil {
user = prestoURL.User.Username()
pass, _ := prestoURL.User.Password()
if pass != "" && prestoURL.Scheme == "https" {
c.auth = prestoURL.User
}
}
for k, v := range map[string]string{
prestoUserHeader: user,
prestoSourceHeader: prestoQuery.Get("source"),
prestoCatalogHeader: prestoQuery.Get("catalog"),
prestoSchemaHeader: prestoQuery.Get("schema"),
prestoSessionHeader: prestoQuery.Get("session_properties"),
} {
if v != "" {
c.httpHeaders.Add(k, v)
}
}
return c, nil
}
// 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...
// },
// },
// }
// presto.RegisterCustomClient("foobar", foobarClient)
// db, err := sql.Open("presto", "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("presto: 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(method, url string, body io.Reader, hs http.Header) (*http.Request, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, fmt.Errorf("presto: %v", err)
}
if c.kerberosEnabled {
err = c.kerberosClient.SetSPNEGOHeader(req, "presto/"+req.URL.Hostname())
if err != nil {
return nil, fmt.Errorf("error setting client SPNEGO header: %v", 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:
timeout := DefaultQueryTimeout
if deadline, ok := ctx.Deadline(); ok {
timeout = deadline.Sub(time.Now())
}
client := c.httpClient
client.Timeout = timeout
resp, err := client.Do(req)
if err != nil {
return nil, &ErrQueryFailed{Reason: err}
}
switch resp.StatusCode {
case http.StatusOK:
return resp, nil
case http.StatusServiceUnavailable:
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 presto failed.
type ErrQueryFailed struct {
StatusCode int
Reason error
}
// Error implements the error interface.
func (e *ErrQueryFailed) Error() string {
return fmt.Sprintf("presto: query failed (%d %s): %q",
e.StatusCode, http.StatusText(e.StatusCode), e.Reason)
}
func newErrQueryFailedFromResponse(resp *http.Response) *ErrQueryFailed {
const maxBytes = 8 * 1024
defer resp.Body.Close()
qf := &ErrQueryFailed{StatusCode: resp.StatusCode}
b, err := ioutil.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
}
var (
_ driver.Stmt = &driverStmt{}
_ driver.StmtQueryContext = &driverStmt{}
)
func (st *driverStmt) Close() error {
return nil
}
func (st *driverStmt) NumInput() int {
return -1
}
func (st *driverStmt) Exec(args []driver.Value) (driver.Result, error) {
return nil, ErrOperationNotSupported
}
type stmtResponse struct {
ID string `json:"id"`
InfoURI string `json:"infoUri"`
NextURI string `json:"nextUri"`
Stats stmtStats `json:"stats"`
Error stmtError `json:"error"`
}
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 int `json:"cpuTimeMillis"`
WallTimeMillis int `json:"wallTimeMillis"`
ProcessedRows int `json:"processedRows"`
ProcessedBytes int `json:"processedBytes"`
RootStage stmtStage `json:"rootStage"`
}
type stmtError struct {
Message string `json:"message"`
ErrorName string `json:"errorName"`
ErrorCode int `json:"errorCode"`
ErrorLocation stmtErrorLocation `json:"errorLocation"`
FailureInfo stmtErrorFailureInfo `json:"failureInfo"`
// Other fields omitted
}
type stmtErrorLocation struct {
LineNumber int `json:"lineNumber"`
ColumnNumber int `json:"columnNumber"`
}
type stmtErrorFailureInfo struct {
Type string `json:"type"`
// Other fields omitted
}
func (e stmtError) Error() string {
return e.FailureInfo.Type + ": " + e.Message
}
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"`
}
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) {
query := st.query
var hs http.Header
if len(args) > 0 {
hs = make(http.Header)
var ss []string
for _, arg := range args {
s, err := Serial(arg.Value)
if err != nil {
return nil, err
}
if arg.Name == prestoUserHeader {
st.user = s
hs.Add(prestoUserHeader, st.user)
} else {
if hs.Get(preparedStatementHeader) == "" {
hs.Add(preparedStatementHeader, preparedStatementName+"="+url.QueryEscape(st.query))
}
ss = append(ss, s)
}
}
query = "EXECUTE " + preparedStatementName + " USING " + strings.Join(ss, ", ")
}
req, err := st.conn.newRequest("POST", st.conn.baseURL+"/v1/statement", strings.NewReader(query), hs)
if err != nil {
return nil, err
}
resp, err := st.conn.roundTrip(ctx, req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var sr stmtResponse
d := json.NewDecoder(resp.Body)
d.UseNumber()
err = d.Decode(&sr)
if err != nil {
return nil, fmt.Errorf("presto: %v", err)
}
err = handleResponseError(resp.StatusCode, sr.Error)
if err != nil {
return nil, err
}
rows := &driverRows{
ctx: ctx,
stmt: st,
nextURI: sr.NextURI,
}
completedChannel := make(chan struct{})
defer close(completedChannel)
go func() {
select {
case <-ctx.Done():
err := rows.Close()
if err != nil {
return
}
case <-completedChannel:
return
}
}()
if err = rows.fetch(false); err != nil {
return nil, err
}
return rows, nil
}
type driverRows struct {
ctx context.Context
stmt *driverStmt
nextURI string
err error
rowindex int
columns []string
coltype []*typeConverter
data []queryData
}
var _ driver.Rows = &driverRows{}
func (qr *driverRows) Close() error {
if qr.nextURI != "" {
hs := make(http.Header)
hs.Add(prestoUserHeader, qr.stmt.user)
req, err := qr.stmt.conn.newRequest("DELETE", qr.nextURI, nil, hs)
if err != nil {
return err
}
ctx, cancel := context.WithDeadline(
context.Background(),
time.Now().Add(DefaultCancelQueryTimeout),
)
defer cancel()
resp, err := qr.stmt.conn.roundTrip(ctx, req)
if err != nil {
qferr, ok := err.(*ErrQueryFailed)
if ok && qferr.StatusCode == http.StatusNoContent {
qr.nextURI = ""
return nil
}
return err
}
resp.Body.Close()
}
return qr.err
}
func (qr *driverRows) Columns() []string {
if qr.err != nil {
return []string{}
}
if qr.columns == nil {
if err := qr.fetch(false); err != nil {
qr.err = err
return []string{}
}
}
return qr.columns
}
var coltypeLengthSuffix = regexp.MustCompile(`\(\d+\)$`)
func (qr *driverRows) ColumnTypeDatabaseTypeName(index int) string {
name := qr.coltype[index].typeName
if m := coltypeLengthSuffix.FindStringSubmatch(name); m != nil {
name = name[0 : len(name)-len(m[0])]
}
return name
}
func (qr *driverRows) Next(dest []driver.Value) error {
if qr.err != nil {
return qr.err
}
if qr.columns == nil || qr.rowindex >= len(qr.data) {
if qr.nextURI == "" {
qr.err = io.EOF
return qr.err
}
if err := qr.fetch(true); err != nil {
qr.err = err
return err
}
}
if len(qr.coltype) == 0 {
qr.err = sql.ErrNoRows
return qr.err
}
for i, v := range qr.coltype {
vv, err := v.ConvertValue(qr.data[qr.rowindex][i])
if err != nil {
qr.err = err
return err
}
dest[i] = vv
}
qr.rowindex++
return nil
}
type queryResponse struct {
ID string `json:"id"`
InfoURI string `json:"infoUri"`
PartialCancelURI string `json:"partialCancelUri"`
NextURI string `json:"nextUri"`
Columns []queryColumn `json:"columns"`
Data []queryData `json:"data"`
Stats stmtStats `json:"stats"`
Error stmtError `json:"error"`
}
type queryColumn struct {
Name string `json:"name"`
Type string `json:"type"`
TypeSignature typeSignature `json:"typeSignature"`
}
type queryData []interface{}
type typeSignature struct {
RawType string `json:"rawType"`
TypeArguments []interface{} `json:"typeArguments"`
LiteralArguments []interface{} `json:"literalArguments"`
}
type infoResponse struct {
QueryID string `json:"queryId"`
State string `json:"state"`
}
func handleResponseError(status int, respErr stmtError) error {
switch respErr.ErrorName {
case "":
return nil
case "USER_CANCELLED":
return ErrQueryCancelled
default:
return &ErrQueryFailed{
StatusCode: status,
Reason: &respErr,
}
}
}
func (qr *driverRows) fetch(allowEOF bool) error {
hs := make(http.Header)
hs.Add(prestoUserHeader, qr.stmt.user)
req, err := qr.stmt.conn.newRequest("GET", qr.nextURI, nil, hs)
if err != nil {
return err
}
resp, err := qr.stmt.conn.roundTrip(qr.ctx, req)
if err != nil {
return err
}
defer resp.Body.Close()
var qresp queryResponse
d := json.NewDecoder(resp.Body)
d.UseNumber()
err = d.Decode(&qresp)
if err != nil {
return fmt.Errorf("presto: %v", err)
}
err = handleResponseError(resp.StatusCode, qresp.Error)
if err != nil {
return err
}
qr.rowindex = 0
qr.data = qresp.Data
qr.nextURI = qresp.NextURI
if len(qr.data) == 0 {
if qr.nextURI != "" {
return qr.fetch(allowEOF)
}
if allowEOF {
return io.EOF
}
}
if qr.columns == nil && len(qresp.Columns) > 0 {
qr.initColumns(&qresp)
}
return nil
}
func (qr *driverRows) initColumns(qresp *queryResponse) {
qr.columns = make([]string, len(qresp.Columns))
qr.coltype = make([]*typeConverter, len(qresp.Columns))
for i, col := range qresp.Columns {
qr.columns[i] = col.Name
qr.coltype[i] = newTypeConverter(col.Type)
}
}
type typeConverter struct {
typeName string
parsedType []string // e.g. array, array, varchar, for [][]string
}
func newTypeConverter(typeName string) *typeConverter {
return &typeConverter{
typeName: typeName,
parsedType: parseType(typeName),
}
}
// parses presto types, e.g. array(varchar(10)) to "array", "varchar"
// TODO: Use queryColumn.TypeSignature instead.
func parseType(name string) []string {
parts := strings.Split(name, "(")
if len(parts) == 1 {
return parts
}
last := len(parts) - 1
parts[last] = strings.TrimRight(parts[last], ")")
if len(parts[last]) > 0 {
if _, err := strconv.Atoi(parts[last]); err == nil {
parts = parts[:last]
}
}
return parts
}
// ConvertValue implements the driver.ValueConverter interface.
func (c *typeConverter) ConvertValue(v interface{}) (driver.Value, error) {
switch strings.ToLower(c.parsedType[0]) {
case "boolean":
vv, err := scanNullBool(v)
if !vv.Valid {
return nil, err
}
return vv.Bool, err
case "json", "char", "varchar", "varbinary", "interval year to month", "interval day to second", "decimal", "ipaddress", "unknown":
vv, err := scanNullString(v)
if !vv.Valid {
return nil, err
}
return vv.String, err
case "tinyint", "smallint", "integer", "bigint":
vv, err := scanNullInt64(v)
if !vv.Valid {
return nil, err
}
return vv.Int64, err
case "real", "double":
vv, err := scanNullFloat64(v)
if !vv.Valid {
return nil, err
}
return vv.Float64, err
case "date", "time", "time with time zone", "timestamp", "timestamp with time zone":
vv, err := scanNullTime(v)
if !vv.Valid {
return nil, err
}
return vv.Time, err
case "map":
if err := validateMap(v); err != nil {
return nil, err
}
return v, nil
case "array":
if err := validateSlice(v); err != nil {
return nil, err
}
return v, nil
default:
return nil, fmt.Errorf("type not supported: %q", c.typeName)
}
}
func validateMap(v interface{}) error {
if v == nil {
return nil
}
if _, ok := v.(map[string]interface{}); !ok {
return fmt.Errorf("cannot convert %v (%T) to map", v, v)
}
return nil
}
func validateSlice(v interface{}) error {
if v == nil {
return nil
}
if _, ok := v.([]interface{}); !ok {
return fmt.Errorf("cannot convert %v (%T) to slice", v, v)
}
return nil
}
func scanNullBool(v interface{}) (sql.NullBool, error) {
if v == nil {
return sql.NullBool{}, nil
}
vv, ok := v.(bool)
if !ok {
return sql.NullBool{},
fmt.Errorf("cannot convert %v (%T) to bool", v, v)
}
return sql.NullBool{Valid: true, Bool: vv}, nil
}
// NullSliceBool represents a slice of bool that may be null.
type NullSliceBool struct {
SliceBool []sql.NullBool
Valid bool
}
// Scan implements the sql.Scanner interface.
func (s *NullSliceBool) Scan(value interface{}) error {
if value == nil {
return nil
}
vs, ok := value.([]interface{})
if !ok {
return fmt.Errorf("presto: cannot convert %v (%T) to []bool", value, value)
}
slice := make([]sql.NullBool, len(vs))
for i := range vs {
v, err := scanNullBool(vs[i])
if err != nil {
return err
}
slice[i] = v
}
s.SliceBool = slice
s.Valid = true
return nil
}
// NullSlice2Bool represents a two-dimensional slice of bool that may be null.
type NullSlice2Bool struct {
Slice2Bool [][]sql.NullBool
Valid bool
}
// Scan implements the sql.Scanner interface.
func (s *NullSlice2Bool) Scan(value interface{}) error {
if value == nil {
return nil
}
vs, ok := value.([]interface{})
if !ok {
return fmt.Errorf("presto: cannot convert %v (%T) to [][]bool", value, value)
}
slice := make([][]sql.NullBool, len(vs))
for i := range vs {
var ss NullSliceBool
if err := ss.Scan(vs[i]); err != nil {
return err
}
slice[i] = ss.SliceBool
}
s.Slice2Bool = slice
s.Valid = true
return nil
}
// NullSlice3Bool implements a three-dimensional slice of bool that may be null.
type NullSlice3Bool struct {
Slice3Bool [][][]sql.NullBool
Valid bool
}
// Scan implements the sql.Scanner interface.
func (s *NullSlice3Bool) Scan(value interface{}) error {
if value == nil {
return nil
}
vs, ok := value.([]interface{})
if !ok {
return fmt.Errorf("presto: cannot convert %v (%T) to [][][]bool", value, value)
}
slice := make([][][]sql.NullBool, len(vs))
for i := range vs {
var ss NullSlice2Bool
if err := ss.Scan(vs[i]); err != nil {
return err
}
slice[i] = ss.Slice2Bool
}
s.Slice3Bool = slice