forked from apache/arrow-adbc
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathstatement.go
More file actions
2029 lines (1825 loc) · 64 KB
/
Copy pathstatement.go
File metadata and controls
2029 lines (1825 loc) · 64 KB
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
package bigquery
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"os"
"runtime"
"slices"
"strconv"
"strings"
"time"
"cloud.google.com/go/aiplatform/apiv1/aiplatformpb"
"cloud.google.com/go/bigquery"
dataprocPB "cloud.google.com/go/dataproc/v2/apiv1/dataprocpb"
"cloud.google.com/go/storage"
"github.com/apache/arrow-adbc/go/adbc"
"github.com/apache/arrow-go/v18/arrow"
"github.com/apache/arrow-go/v18/arrow/array"
"github.com/apache/arrow-go/v18/arrow/ipc"
"github.com/apache/arrow-go/v18/arrow/memory"
"github.com/stretchr/testify/assert/yaml"
"google.golang.org/api/iterator"
"google.golang.org/protobuf/encoding/protojson"
)
const (
ContextKeyUseStorageApiDisabledClient = "USE_STORAGE_API_DISABLED_CLIENT"
)
// todos for bigqueryConfig
// - TableDefinitions
// - Parameters
// - TimePartitioning
// - RangePartitioning
// - Clustering
// - Labels
// - DestinationEncryptionConfig
// - SchemaUpdateOptions
// - ConnectionProperties
type statement struct {
alloc memory.Allocator
cnxn *connectionImpl
queryConfig bigquery.QueryConfig
parameterMode string
paramBinding arrow.RecordBatch
streamBinding array.RecordReader
resultRecordBufferSize int
prefetchConcurrency int
useStorageApiDisabledClient bool
// Ingest related fields
ingestPath string
ingestFileDelimiter string
explicitSchema []*bigquery.FieldSchema
// DataProc Fields
dataprocRegion string
dataprocProject string
dataprocPoolingTimeout int
// DataProc Create Batch fields
createBatchReqParent string
createBatchReqBatchYML string
createBatchReqBatchId string
// DataProc Submit Job fields
submitJobReqClusterName string
submitJobReqGCSPath string
// GCS fields
writeGCSBucket string
writeGCSObjectName string
writeGCSContent string
//Notebook Execute Job
createNotebookExecuteJobGscPath string
createNotebookExecuteJobModelFileName string
createNotebookExecuteJobModelName string
createNotebookExecuteJobGCSBucket string
createNotebookExecuteJobTemplateId string
createNotebookExecuteJobParent string
createNotebookExecuteJobProject string
createNotebookExecuteJobRegion string
// Field that contains Table.update columns descriptions
updateTableColumnsDescription string
// Field that contains Table.update columns policy tags
updateTableColumnsPolicyTags string
// Field that contains the JSON string to authorize a view to source datasets
authorizeViewToDatasets string
// Field that contains the table description to update
tableDescription string
// Copy table fields
copyTableSource string
copyTableDestination string
copyTableWriteDisposition string
// Wrap errors with a link to failed job
linkFailedJob bool
// Fetch BigQuery job statistics. Off by default.
fetchJobStats bool
}
func (st *statement) GetOptionBytes(key string) ([]byte, error) {
return nil, adbc.Error{
Msg: fmt.Sprintf("[BigQuery] Unknown statement option '%s'", key),
Code: adbc.StatusNotFound,
}
}
func (st *statement) GetOptionDouble(key string) (float64, error) {
return 0, adbc.Error{
Msg: fmt.Sprintf("[BigQuery] Unknown statement option '%s'", key),
Code: adbc.StatusNotFound,
}
}
func (st *statement) SetOptionBytes(key string, value []byte) error {
switch key {
case OptionStringIngestSchema:
return st.loadExplicitSchema(value)
default:
return adbc.Error{
Msg: fmt.Sprintf("[BigQuery] Unknown statement option '%s'", key),
Code: adbc.StatusNotImplemented,
}
}
}
func (st *statement) SetOptionDouble(key string, value float64) error {
return adbc.Error{
Msg: fmt.Sprintf("[BigQuery] Unknown statement option '%s'", key),
Code: adbc.StatusNotImplemented,
}
}
// Close releases any relevant resources associated with this statement
// and closes it (particularly if it is a prepared statement).
//
// A statement instance should not be used after Close is called.
func (st *statement) Close() error {
if st.cnxn == nil {
return adbc.Error{
Msg: "statement already closed",
Code: adbc.StatusInvalidState}
}
st.clearParameters()
st.cnxn = nil
return nil
}
func (st *statement) GetOption(key string) (string, error) {
switch key {
case OptionStringProjectID:
val, err := st.cnxn.GetOption(OptionStringProjectID)
if err != nil {
return "", err
} else {
return val, nil
}
case OptionStringQueryParameterMode:
return st.parameterMode, nil
case OptionStringQueryDefaultProjectID:
return st.queryConfig.DefaultProjectID, nil
case OptionStringQueryDefaultDatasetID:
return st.queryConfig.DefaultDatasetID, nil
case OptionStringQueryCreateDisposition:
return string(st.queryConfig.CreateDisposition), nil
case OptionStringQueryWriteDisposition:
return string(st.queryConfig.WriteDisposition), nil
case OptionStringQueryLabels:
encoded, err := json.Marshal(st.queryConfig.Labels)
if err != nil {
return "", err
}
return string(encoded), nil
case OptionBoolQueryDisableQueryCache:
return strconv.FormatBool(st.queryConfig.DisableQueryCache), nil
case OptionBoolDisableFlattenedResults:
return strconv.FormatBool(st.queryConfig.DisableFlattenedResults), nil
case OptionBoolQueryAllowLargeResults:
return strconv.FormatBool(st.queryConfig.AllowLargeResults), nil
case OptionStringQueryPriority:
return string(st.queryConfig.Priority), nil
case OptionBoolQueryUseLegacySQL:
return strconv.FormatBool(st.queryConfig.UseLegacySQL), nil
case OptionBoolQueryDryRun:
return strconv.FormatBool(st.queryConfig.DryRun), nil
case OptionBoolQueryCreateSession:
return strconv.FormatBool(st.queryConfig.CreateSession), nil
case OptionBoolQueryLinkFailedJob:
return strconv.FormatBool(st.linkFailedJob), nil
case OptionBoolStatementFetchJobStats:
return strconv.FormatBool(st.fetchJobStats), nil
case OptionBoolUseStorageApiDisabledClient:
return strconv.FormatBool(st.useStorageApiDisabledClient), nil
case OptionStringIngestFileDelimiter:
return st.ingestFileDelimiter, nil
case OptionStringIngestPath:
return st.ingestPath, nil
case OptionJsonUpdateTableColumnsDescription:
return st.updateTableColumnsDescription, nil
case OptionJsonUpdateTableColumnsPolicyTags:
return st.updateTableColumnsPolicyTags, nil
case OptionStringUpdateTableDescriptionValue:
return st.tableDescription, nil
case OptionJsonAuthorizeViewToDatasets:
return st.authorizeViewToDatasets, nil
case OptionStringDataprocReqRegion:
return st.dataprocRegion, nil
case OptionStringDataprocReqProject:
return st.dataprocProject, nil
case OptionStringCreateBatchReqParent:
return st.createBatchReqParent, nil
case OptionStringCreateBatchReqBatchYML:
return st.createBatchReqBatchYML, nil
case OptionStringCreateBatchReqBatchId:
return st.createBatchReqBatchId, nil
case OptionStringDataprocSubmitJobReqClusterName:
return st.submitJobReqClusterName, nil
case OptionStringDataprocSubmitJobReqGCSPath:
return st.submitJobReqGCSPath, nil
case OptionStringWriteGCSBucket:
return st.writeGCSBucket, nil
case OptionStringWriteGCSObjectName:
return st.writeGCSObjectName, nil
case OptionStringWriteGCSContent:
return st.writeGCSContent, nil
case OptionStringNotebookExecuteJobGscPath:
return st.createNotebookExecuteJobGscPath, nil
case OptionStringNotebookExecuteJobModelFileName:
return st.createNotebookExecuteJobModelFileName, nil
case OptionStringNotebookExecuteJobModelName:
return st.createNotebookExecuteJobModelName, nil
case OptionStringNotebookExecuteJobGscBucket:
return st.createNotebookExecuteJobGCSBucket, nil
case OptionStringNotebookExecuteJobTemplateId:
return st.createNotebookExecuteJobTemplateId, nil
case OptionStringNotebookExecuteJobParent:
return st.createNotebookExecuteJobParent, nil
case OptionStringNotebookExecuteJobProject:
return st.createNotebookExecuteJobProject, nil
case OptionStringNotebookExecuteJobRegion:
return st.createNotebookExecuteJobRegion, nil
case OptionStringCopyTableSource:
return st.copyTableSource, nil
case OptionStringCopyTableDestination:
return st.copyTableDestination, nil
case OptionStringCopyTableWriteDisposition:
return st.copyTableWriteDisposition, nil
default:
val, err := st.cnxn.GetOption(key)
if err == nil {
return val, nil
}
return "", err
}
}
func (st *statement) GetOptionInt(key string) (int64, error) {
switch key {
case OptionIntQueryMaxBillingTier:
return int64(st.queryConfig.MaxBillingTier), nil
case OptionIntQueryMaxBytesBilled:
return st.queryConfig.MaxBytesBilled, nil
case OptionIntQueryJobTimeout:
return st.queryConfig.JobTimeout.Milliseconds(), nil
case OptionIntQueryResultBufferSize:
return int64(st.resultRecordBufferSize), nil
case OptionIntQueryPrefetchConcurrency:
return int64(st.prefetchConcurrency), nil
case OptionIntDataprocReqPoolingTimeout:
return int64(st.dataprocPoolingTimeout), nil
case OptionBoolUseStorageApiDisabledClient:
if st.useStorageApiDisabledClient {
return 1, nil
}
return 0, nil
default:
val, err := st.cnxn.GetOptionInt(key)
if err == nil {
return val, nil
}
return 0, err
}
}
func (st *statement) SetOption(key string, v string) error {
switch key {
case OptionStringQueryParameterMode:
switch v {
case OptionValueQueryParameterModeNamed, OptionValueQueryParameterModePositional:
st.parameterMode = v
default:
return adbc.Error{
Code: adbc.StatusInvalidArgument,
Msg: fmt.Sprintf("Parameter mode for the statement can only be either %s or %s", OptionValueQueryParameterModeNamed, OptionValueQueryParameterModePositional),
}
}
case OptionStringQueryDestinationTable:
val, err := stringToTable(st, v)
if err == nil {
st.queryConfig.Dst = val
} else {
return err
}
case OptionStringQueryDefaultProjectID:
st.queryConfig.DefaultProjectID = v
case OptionStringQueryDefaultDatasetID:
st.queryConfig.DefaultDatasetID = v
case OptionStringQueryCreateDisposition:
val, err := stringToTableCreateDisposition(v)
if err == nil {
st.queryConfig.CreateDisposition = val
} else {
return err
}
case OptionStringQueryWriteDisposition:
val, err := stringToTableWriteDisposition(v)
if err == nil {
st.queryConfig.WriteDisposition = val
} else {
return err
}
case OptionStringQueryLabels:
var labels map[string]string
err := json.Unmarshal([]byte(v), &labels)
if err == nil {
st.queryConfig.Labels = labels
} else {
return err
}
case OptionBoolQueryDisableQueryCache:
val, err := strconv.ParseBool(v)
if err == nil {
st.queryConfig.DisableQueryCache = val
} else {
return err
}
case OptionBoolDisableFlattenedResults:
val, err := strconv.ParseBool(v)
if err == nil {
st.queryConfig.DisableFlattenedResults = val
} else {
return err
}
case OptionBoolQueryAllowLargeResults:
val, err := strconv.ParseBool(v)
if err == nil {
st.queryConfig.AllowLargeResults = val
} else {
return err
}
case OptionStringQueryPriority:
val, err := stringToQueryPriority(v)
if err == nil {
st.queryConfig.Priority = val
} else {
return err
}
case OptionBoolQueryUseLegacySQL:
val, err := strconv.ParseBool(v)
if err == nil {
st.queryConfig.UseLegacySQL = val
} else {
return err
}
case OptionBoolQueryDryRun:
val, err := strconv.ParseBool(v)
if err == nil {
st.queryConfig.DryRun = val
} else {
return err
}
case OptionBoolQueryCreateSession:
val, err := strconv.ParseBool(v)
if err == nil {
st.queryConfig.CreateSession = val
} else {
return err
}
case OptionStringIngestPath:
st.ingestPath = v
case OptionStringIngestFileDelimiter:
st.ingestFileDelimiter = v
case OptionStringDataprocReqRegion:
st.dataprocRegion = v
case OptionStringDataprocReqProject:
st.dataprocProject = v
case OptionStringCreateBatchReqParent:
st.createBatchReqParent = v
case OptionStringCreateBatchReqBatchYML:
st.createBatchReqBatchYML = v
case OptionStringCreateBatchReqBatchId:
st.createBatchReqBatchId = v
case OptionStringDataprocSubmitJobReqClusterName:
st.submitJobReqClusterName = v
case OptionStringDataprocSubmitJobReqGCSPath:
st.submitJobReqGCSPath = v
case OptionStringWriteGCSBucket:
st.writeGCSBucket = v
case OptionStringWriteGCSObjectName:
st.writeGCSObjectName = v
case OptionStringWriteGCSContent:
st.writeGCSContent = v
case OptionStringCopyTableSource:
st.copyTableSource = v
case OptionStringCopyTableDestination:
st.copyTableDestination = v
case OptionStringCopyTableWriteDisposition:
st.copyTableWriteDisposition = v
case OptionJsonUpdateTableColumnsDescription:
st.updateTableColumnsDescription = v
case OptionJsonUpdateTableColumnsPolicyTags:
st.updateTableColumnsPolicyTags = v
case OptionIntDataprocReqPoolingTimeout:
val, err := strconv.ParseInt(v, 10, strconv.IntSize)
if err == nil {
st.dataprocPoolingTimeout = int(val)
} else {
return err
}
return nil
case OptionJsonAuthorizeViewToDatasets:
st.authorizeViewToDatasets = v
case OptionStringUpdateTableDescriptionValue:
st.tableDescription = v
return nil
case OptionBoolQueryLinkFailedJob:
val, err := strconv.ParseBool(v)
if err == nil {
st.linkFailedJob = val
} else {
return err
}
case OptionBoolStatementFetchJobStats:
val, err := strconv.ParseBool(v)
if err == nil {
st.fetchJobStats = val
} else {
return err
}
case OptionStringNotebookExecuteJobGscPath:
st.createNotebookExecuteJobGscPath = v
case OptionStringNotebookExecuteJobModelFileName:
st.createNotebookExecuteJobModelFileName = v
case OptionStringNotebookExecuteJobModelName:
st.createNotebookExecuteJobModelName = v
case OptionStringNotebookExecuteJobGscBucket:
st.createNotebookExecuteJobGCSBucket = v
case OptionStringNotebookExecuteJobTemplateId:
st.createNotebookExecuteJobTemplateId = v
case OptionStringNotebookExecuteJobParent:
st.createNotebookExecuteJobParent = v
case OptionStringNotebookExecuteJobProject:
st.createNotebookExecuteJobProject = v
case OptionStringNotebookExecuteJobRegion:
st.createNotebookExecuteJobRegion = v
case OptionBoolUseStorageApiDisabledClient:
val, err := strconv.ParseBool(v)
if err == nil {
st.useStorageApiDisabledClient = val
} else {
return err
}
return nil
default:
return adbc.Error{
Code: adbc.StatusInvalidArgument,
Msg: fmt.Sprintf("unknown statement string type option `%s`", key),
}
}
return nil
}
func (st *statement) SetOptionInt(key string, value int64) error {
switch key {
case OptionIntQueryMaxBillingTier:
st.queryConfig.MaxBillingTier = int(value)
case OptionIntQueryMaxBytesBilled:
st.queryConfig.MaxBytesBilled = value
case OptionIntQueryJobTimeout:
st.queryConfig.JobTimeout = time.Duration(value) * time.Millisecond
case OptionIntQueryResultBufferSize:
st.resultRecordBufferSize = int(value)
return nil
case OptionIntQueryPrefetchConcurrency:
st.prefetchConcurrency = int(value)
return nil
case OptionIntDataprocReqPoolingTimeout:
st.dataprocPoolingTimeout = int(value)
return nil
default:
return adbc.Error{
Code: adbc.StatusInvalidArgument,
Msg: fmt.Sprintf("unknown statement string type option `%s`", key),
}
}
return nil
}
// SetSqlQuery sets the query string to be executed.
//
// The query can then be executed with any of the Execute methods.
// For queries expected to be executed repeatedly, Prepare should be
// called before execution.
func (st *statement) SetSqlQuery(query string) error {
st.queryConfig.Q = query
return nil
}
// ExecuteQuery executes the current query or prepared statement
// and returns a RecordReader for the results along with the number
// of rows affected if known, otherwise it will be -1.
//
// This invalidates any prior result sets on this statement.
func (st *statement) ExecuteQuery(ctx context.Context) (array.RecordReader, int64, error) {
if st.ingestPath != "" {
return st.executeIngest(ctx)
}
if st.createBatchReqParent != "" {
return st.executeDataprocCreateBatch(ctx)
}
if st.submitJobReqClusterName != "" {
return st.executeSubmitJobAsOperation(ctx)
}
if st.createNotebookExecuteJobParent != "" {
return st.executeCreateNotebookExecutionJob(ctx)
}
if st.writeGCSBucket != "" {
return st.writeToGCS(ctx)
}
if st.copyTableSource != "" {
return st.executeCopyTable(ctx)
}
if st.updateTableColumnsDescription != "" || st.updateTableColumnsPolicyTags != "" {
return st.executeUpdateTableColumnsMetadata(ctx)
}
if st.tableDescription != "" {
return st.executeUpdateTableDescription(ctx)
}
if st.authorizeViewToDatasets != "" {
return st.executeAuthorizeViewToDatasets(ctx)
}
if st.queryConfig.Q == "" {
return nil, -1, adbc.Error{
Msg: "cannot execute without a query",
Code: adbc.StatusInvalidState,
}
}
rdr, err := st.getBoundParameterReader()
if err != nil {
return nil, -1, err
}
ctx = context.WithValue(ctx, ContextKeyUseStorageApiDisabledClient, st.useStorageApiDisabledClient)
return newRecordReader(ctx, st.query(), rdr, st.parameterMode, st.cnxn.Alloc, st.resultRecordBufferSize, st.prefetchConcurrency, st.linkFailedJob, st.fetchJobStats)
}
// ExecuteUpdate executes a statement that does not generate a result
// set. It returns the number of rows affected if known, otherwise -1.
func (st *statement) ExecuteUpdate(ctx context.Context) (int64, error) {
boundParameters, err := st.getBoundParameterReader()
if err != nil {
return -1, err
}
if boundParameters == nil {
return runUpdate(ctx, st.query())
}
totalRows := int64(0)
for boundParameters.Next() {
values := boundParameters.RecordBatch()
for i := 0; i < int(values.NumRows()); i++ {
parameters, err := getQueryParameter(values, i, st.parameterMode)
if err != nil {
return -1, err
}
if parameters != nil {
st.queryConfig.Parameters = parameters
}
currentRows, err := runUpdate(ctx, st.query())
if err != nil {
return -1, err
}
totalRows += currentRows
}
}
return totalRows, nil
}
// ExecuteSchema gets the schema of the result set of a query without executing it.
func (st *statement) ExecuteSchema(ctx context.Context) (*arrow.Schema, error) {
return nil, adbc.Error{
Code: adbc.StatusNotImplemented,
Msg: "ExecuteSchema not yet implemented for BigQuery driver",
}
}
// Prepare turns this statement into a prepared statement to be executed
// multiple times. This invalidates any prior result sets.
func (st *statement) Prepare(_ context.Context) error {
if st.queryConfig.Q == "" {
return adbc.Error{
Code: adbc.StatusInvalidState,
Msg: "cannot prepare statement with no query",
}
}
// bigquery doesn't provide a "Prepare" api, this is a no-op
return nil
}
// SetSubstraitPlan allows setting a serialized Substrait execution
// plan into the query or for querying Substrait-related metadata.
//
// Drivers are not required to support both SQL and Substrait semantics.
// If they do, it may be via converting between representations internally.
//
// Like SetSqlQuery, after this is called the query can be executed
// using any of the Execute methods. If the query is expected to be
// executed repeatedly, Prepare should be called first on the statement.
func (st *statement) SetSubstraitPlan(plan []byte) error {
return adbc.Error{
Code: adbc.StatusNotImplemented,
Msg: "Substrait not yet implemented for BigQuery driver",
}
}
func (st *statement) query() *bigquery.Query {
var query *bigquery.Query
if st.useStorageApiDisabledClient && st.cnxn.clientStorageApiDisabled != nil {
query = st.cnxn.clientStorageApiDisabled.Query("")
} else {
query = st.cnxn.client.Query("")
}
query.QueryConfig = st.queryConfig
return query
}
func arrowDataTypeToTypeKind(field arrow.Field, value arrow.Array) (bigquery.StandardSQLDataType, error) {
// https://cloud.google.com/bigquery/docs/reference/storage#arrow_schema_details
// https://cloud.google.com/bigquery/docs/reference/rest/v2/StandardSqlDataType#typekind
switch value.DataType().ID() {
case arrow.BOOL:
return bigquery.StandardSQLDataType{
TypeKind: "BOOL",
}, nil
case arrow.INT8, arrow.INT16, arrow.INT32, arrow.INT64, arrow.UINT8, arrow.UINT16, arrow.UINT32, arrow.UINT64:
return bigquery.StandardSQLDataType{
TypeKind: "INT64",
}, nil
case arrow.FLOAT16, arrow.FLOAT32, arrow.FLOAT64:
return bigquery.StandardSQLDataType{
TypeKind: "FLOAT64",
}, nil
case arrow.BINARY, arrow.BINARY_VIEW, arrow.LARGE_BINARY, arrow.FIXED_SIZE_BINARY:
return bigquery.StandardSQLDataType{
TypeKind: "BYTES",
}, nil
case arrow.STRING, arrow.STRING_VIEW, arrow.LARGE_STRING:
return bigquery.StandardSQLDataType{
TypeKind: "STRING",
}, nil
case arrow.DATE32, arrow.DATE64:
return bigquery.StandardSQLDataType{
TypeKind: "DATE",
}, nil
case arrow.TIMESTAMP:
return bigquery.StandardSQLDataType{
TypeKind: "TIMESTAMP",
}, nil
case arrow.TIME32, arrow.TIME64:
return bigquery.StandardSQLDataType{
TypeKind: "TIME",
}, nil
case arrow.DECIMAL128:
return bigquery.StandardSQLDataType{
TypeKind: "NUMERIC",
}, nil
case arrow.DECIMAL256:
return bigquery.StandardSQLDataType{
TypeKind: "BIGNUMERIC",
}, nil
case arrow.LIST, arrow.LARGE_LIST, arrow.FIXED_SIZE_LIST, arrow.LIST_VIEW, arrow.LARGE_LIST_VIEW:
elemField := field.Type.(*arrow.ListType).ElemField()
elemType, err := arrowDataTypeToTypeKind(elemField, value.(*array.List).ListValues())
if err != nil {
return bigquery.StandardSQLDataType{}, err
}
return bigquery.StandardSQLDataType{
TypeKind: "ARRAY",
ArrayElementType: &elemType,
}, nil
case arrow.STRUCT:
numFields := value.(*array.Struct).NumField()
structType := bigquery.StandardSQLStructType{
Fields: make([]*bigquery.StandardSQLField, 0),
}
for i := 0; i < numFields; i++ {
currentField := field.Type.(*arrow.StructType).Field(i)
currentFieldArray := value.(*array.Struct).Field(i)
childType, err := arrowDataTypeToTypeKind(currentField, currentFieldArray)
if err != nil {
return bigquery.StandardSQLDataType{}, err
}
sqlField := bigquery.StandardSQLField{
Name: currentField.Name,
Type: &childType,
}
structType.Fields = append(structType.Fields, &sqlField)
}
return bigquery.StandardSQLDataType{
TypeKind: "STRUCT",
StructType: &structType,
}, nil
case arrow.INTERVAL_MONTHS, arrow.INTERVAL_DAY_TIME, arrow.INTERVAL_MONTH_DAY_NANO:
// "INTERVAL" is not yet documented in BigQuery docs, but it works in
// practice here for our puposes.
return bigquery.StandardSQLDataType{
TypeKind: "INTERVAL",
}, nil
default:
// todo: implement all other types
//
// - arrow.DURATION
// For arrow.DURATION, I'm not sure which SQL DataType would be a good
// representation for it. `DATETIME` could be a potential one for it,
// if we count from `0000-01-01T00:00:00.000000Z`
//
// - arrow.INTERVAL_MONTHS
// - arrow.INTERVAL_DAY_TIME
// - arrow.INTERVAL_MONTH_DAY_NANO
//
// - arrow.RUN_END_ENCODED
// - arrow.SPARSE_UNION
// - arrow.DENSE_UNION
// - arrow.DICTIONARY
// - arrow.MAP
return bigquery.StandardSQLDataType{}, adbc.Error{
Code: adbc.StatusNotImplemented,
Msg: fmt.Sprintf("Parameter type %v is not yet implemented for BigQuery driver", value.DataType().ID()),
}
}
}
func arrowValueToQueryParameterValue(field arrow.Field, value arrow.Array, i int) (bigquery.QueryParameter, error) {
// https://cloud.google.com/bigquery/docs/reference/storage#arrow_schema_details
// https://cloud.google.com/bigquery/docs/reference/rest/v2/StandardSqlDataType#typekind
parameter := bigquery.QueryParameter{}
sqlDataType, err := arrowDataTypeToTypeKind(field, value)
if err != nil {
return bigquery.QueryParameter{}, err
}
if value.IsNull(i) {
parameter.Value = &bigquery.QueryParameterValue{
Type: sqlDataType,
Value: "NULL",
}
return parameter, nil
}
switch value.DataType().ID() {
case arrow.BOOL:
parameter.Value = &bigquery.QueryParameterValue{
Type: sqlDataType,
Value: value.ValueStr(i),
}
case arrow.INT8, arrow.INT16, arrow.INT32, arrow.INT64, arrow.UINT8, arrow.UINT16, arrow.UINT32, arrow.UINT64:
parameter.Value = &bigquery.QueryParameterValue{
Type: sqlDataType,
Value: value.ValueStr(i),
}
case arrow.FLOAT16, arrow.FLOAT32, arrow.FLOAT64:
parameter.Value = &bigquery.QueryParameterValue{
Type: sqlDataType,
Value: value.ValueStr(i),
}
case arrow.BINARY, arrow.BINARY_VIEW, arrow.LARGE_BINARY, arrow.FIXED_SIZE_BINARY:
// Encoded as a base64 string per RFC 4648, section 4.
parameter.Value = &bigquery.QueryParameterValue{
Type: sqlDataType,
Value: value.ValueStr(i),
}
case arrow.STRING, arrow.STRING_VIEW, arrow.LARGE_STRING:
parameter.Value = &bigquery.QueryParameterValue{
Type: sqlDataType,
Value: value.ValueStr(i),
}
case arrow.DATE32:
// Encoded as RFC 3339 full-date format string: 1985-04-12
parameter.Value = &bigquery.QueryParameterValue{
Type: sqlDataType,
Value: value.ValueStr(i),
}
case arrow.DATE64:
// Encoded as RFC 3339 full-date format string: 1985-04-12
parameter.Value = &bigquery.QueryParameterValue{
Type: sqlDataType,
Value: value.ValueStr(i),
}
case arrow.TIMESTAMP:
// Encoded as an RFC 3339 timestamp with mandatory "Z" time zone string: 1985-04-12T23:20:50.52Z
// BigQuery can only do microsecond resolution
toTime, _ := value.DataType().(*arrow.TimestampType).GetToTimeFunc()
encoded := toTime(value.(*array.Timestamp).Value(i)).Format("2006-01-02T15:04:05.999999Z07:00")
parameter.Value = &bigquery.QueryParameterValue{
Type: sqlDataType,
Value: encoded,
}
case arrow.TIME32:
// Encoded as RFC 3339 partial-time format string: 23:20:50.52
encoded := value.(*array.Time32).Value(i).FormattedString(value.DataType().(*arrow.Time32Type).Unit)
parameter.Value = &bigquery.QueryParameterValue{
Type: sqlDataType,
Value: encoded,
}
case arrow.TIME64:
// Encoded as RFC 3339 partial-time format string: 23:20:50.52
//
// cannot use the default format, which will cause errors like
// googleapi: Error 400: Unparsable query parameter `` in type `TYPE_TIME`,
// Invalid time string "00:00:00.000000001" value: '00:00:00.000000001', invalid
encoded := value.(*array.Time64).Value(i).FormattedString(arrow.Microsecond)
parameter.Value = &bigquery.QueryParameterValue{
Type: sqlDataType,
Value: encoded,
}
case arrow.DECIMAL128:
parameter.Value = &bigquery.QueryParameterValue{
Type: sqlDataType,
Value: value.ValueStr(i),
}
case arrow.DECIMAL256:
parameter.Value = &bigquery.QueryParameterValue{
Type: sqlDataType,
Value: value.ValueStr(i),
}
case arrow.LIST, arrow.FIXED_SIZE_LIST, arrow.LIST_VIEW:
start, end := value.(*array.List).ValueOffsets(i)
elemField := field.Type.(*arrow.ListType).ElemField()
arrayValues := make([]bigquery.QueryParameterValue, end-start)
for row := start; row < end; row++ {
pv, err := arrowValueToQueryParameterValue(elemField, value.(*array.List).ListValues(), int(row))
if err != nil {
return bigquery.QueryParameter{}, err
}
arrayValues[row-start].Value = pv.Value
}
parameter.Value = &bigquery.QueryParameterValue{
Type: sqlDataType,
ArrayValue: arrayValues,
}
case arrow.LARGE_LIST_VIEW:
start, end := value.(*array.LargeListView).ValueOffsets(i)
elemField := field.Type.(*arrow.LargeListType).ElemField()
arrayValues := make([]bigquery.QueryParameterValue, end-start)
for row := start; row < end; row++ {
pv, err := arrowValueToQueryParameterValue(elemField, value.(*array.LargeListView).ListValues(), int(row))
if err != nil {
return bigquery.QueryParameter{}, err
}
arrayValues[row-start].Value = pv.Value
}
parameter.Value = &bigquery.QueryParameterValue{
Type: sqlDataType,
ArrayValue: arrayValues,
}
case arrow.STRUCT:
numFields := value.(*array.Struct).NumField()
childFields := field.Type.(*arrow.StructType).Fields()
structValues := make(map[string]bigquery.QueryParameterValue)
for j := 0; j < numFields; j++ {
currentField := childFields[j]
fieldName := currentField.Name
if len(fieldName) == 0 {
return bigquery.QueryParameter{}, adbc.Error{
Code: adbc.StatusInvalidArgument,
Msg: "child field name cannot be empty for structs",
}
}
currentFieldArray := value.(*array.Struct).Field(j)
pv, err := arrowValueToQueryParameterValue(currentField, currentFieldArray, i)
if err != nil {
return bigquery.QueryParameter{}, err
}
_, found := structValues[fieldName]
if found {
return bigquery.QueryParameter{}, adbc.Error{
Code: adbc.StatusInvalidArgument,
Msg: fmt.Sprintf("duplicated child field `%s` found in structs", fieldName),
}
}
structValues[fieldName] = *pv.Value.(*bigquery.QueryParameterValue)
}
parameter.Value = &bigquery.QueryParameterValue{
Type: sqlDataType,
StructValue: structValues,
}
default:
// todo: implement all other types
return parameter, adbc.Error{
Code: adbc.StatusNotImplemented,
Msg: fmt.Sprintf("Parameter type %v is not yet implemented for BigQuery driver", value.DataType().ID()),
}
}
return parameter, nil
}
func (st *statement) getBoundParameterReader() (array.RecordReader, error) {
if st.paramBinding != nil {
rdr, err := array.NewRecordReader(st.paramBinding.Schema(), []arrow.RecordBatch{st.paramBinding})
if err != nil {
return nil, err
}
st.streamBinding = rdr
return st.streamBinding, nil
} else if st.streamBinding != nil {
return st.streamBinding, nil
} else {
return nil, nil
}
}
func (st *statement) clearParameters() {
if st.paramBinding != nil {
st.paramBinding.Release()
st.paramBinding = nil
}
if st.streamBinding != nil {
st.streamBinding.Release()
st.streamBinding = nil
}
}
// SetParameters takes a record batch to send as the parameter bindings when
// executing. It should match the schema from ParameterSchema.
//
// This will call Retain on the record to ensure it doesn't get released out
// from under the statement. Release will be called on a previous binding
// record or reader if it existed, and will be called upon calling Close on the
// PreparedStatement.
func (st *statement) SetParameters(binding arrow.RecordBatch) {
st.clearParameters()
st.paramBinding = binding
if st.paramBinding != nil {
st.paramBinding.Retain()
}
}
// SetRecordReader takes a RecordReader to send as the parameter bindings when
// executing. It should match the schema from ParameterSchema.
//
// This will call Retain on the reader to ensure it doesn't get released out
// from under the statement. Release will be called on a previous binding
// record or reader if it existed, and will be called upon calling Close on the
// PreparedStatement.
func (st *statement) SetRecordReader(binding array.RecordReader) {