forked from googleapis/google-cloud-ruby
-
Notifications
You must be signed in to change notification settings - Fork 2
/
project.rb
1800 lines (1755 loc) · 80.4 KB
/
project.rb
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 2015 Google LLC
#
# 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
#
# https://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.
require "google/cloud/errors"
require "google/cloud/bigquery/service"
require "google/cloud/bigquery/credentials"
require "google/cloud/bigquery/dataset"
require "google/cloud/bigquery/job"
require "google/cloud/bigquery/external"
require "google/cloud/bigquery/project/list"
require "google/cloud/bigquery/time"
require "google/cloud/bigquery/schema"
module Google
module Cloud
module Bigquery
##
# # Project
#
# Projects are top-level containers in Google Cloud Platform. They store
# information about billing and authorized users, and they contain
# BigQuery data. Each project has a friendly name and a unique ID.
#
# Google::Cloud::Bigquery::Project is the main object for interacting with
# Google BigQuery. {Google::Cloud::Bigquery::Dataset} objects are created,
# accessed, and deleted by Google::Cloud::Bigquery::Project.
#
# See {Google::Cloud#bigquery}.
#
# @attr_reader [String, nil] name The descriptive name of the project.
# Can only be present if the project was retrieved with {#projects}.
# @attr_reader [Integer, nil] numeric_id The numeric ID of the project.
# Can only be present if the project was retrieved with {#projects}.
#
# @example
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
# dataset = bigquery.dataset "my_dataset"
# table = dataset.table "my_table"
#
class Project
##
# @private The Service object.
attr_accessor :service
attr_reader :name
attr_reader :numeric_id
##
# Creates a new Service instance.
#
# See {Google::Cloud.bigquery}
def initialize service
@service = service
end
##
# The BigQuery project connected to.
#
# @example
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new(
# project_id: "my-project",
# credentials: "/path/to/keyfile.json"
# )
#
# bigquery.project_id #=> "my-project"
#
def project_id
service.project
end
alias project project_id
##
# The email address of the service account for the project used to
# connect to BigQuery. (See also {#project_id}.)
#
# @return [String] The service account email address.
#
def service_account_email
@service_account_email ||= service.project_service_account.email
end
##
# Copies the data from the source table to the destination table using
# an asynchronous method. In this method, a {CopyJob} is immediately
# returned. The caller may poll the service by repeatedly calling
# {Job#reload!} and {Job#done?} to detect when the job is done, or
# simply block until the job is done by calling #{Job#wait_until_done!}.
# See {#copy} for the synchronous version. Use this method instead of
# {Table#copy_job} to copy from source tables in other projects.
#
# The geographic location for the job ("US", "EU", etc.) can be set via
# {CopyJob::Updater#location=} in a block passed to this method.
#
# @param [String, Table] source_table The source table for the
# copied data. This can be a table object; or a string ID as specified
# by the [Standard SQL Query
# Reference](https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#from-clause)
# (`project-name.dataset_id.table_id`) or the [Legacy SQL Query
# Reference](https://cloud.google.com/bigquery/query-reference#from)
# (`project-name:dataset_id.table_id`).
# @param [String, Table] destination_table The destination table for the
# copied data. This can be a table object; or a string ID as specified
# by the [Standard SQL Query
# Reference](https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#from-clause)
# (`project-name.dataset_id.table_id`) or the [Legacy SQL Query
# Reference](https://cloud.google.com/bigquery/query-reference#from)
# (`project-name:dataset_id.table_id`).
# @param [String] create Specifies whether the job is allowed to create
# new tables. The default value is `needed`.
#
# The following values are supported:
#
# * `needed` - Create the table if it does not exist.
# * `never` - The table must already exist. A 'notFound' error is
# raised if the table does not exist.
# @param [String] write Specifies how to handle data already present in
# the destination table. The default value is `empty`.
#
# The following values are supported:
#
# * `truncate` - BigQuery overwrites the table data.
# * `append` - BigQuery appends the data to the table.
# * `empty` - An error will be returned if the destination table
# already contains data.
# @param [String] job_id A user-defined ID for the copy job. The ID
# must contain only letters (`[A-Za-z]`), numbers (`[0-9]`), underscores
# (`_`), or dashes (`-`). The maximum length is 1,024 characters. If
# `job_id` is provided, then `prefix` will not be used.
#
# See [Generating a job
# ID](https://cloud.google.com/bigquery/docs/managing-jobs#generate-jobid).
# @param [String] prefix A string, usually human-readable, that will be
# prepended to a generated value to produce a unique job ID. For
# example, the prefix `daily_import_job_` can be given to generate a
# job ID such as `daily_import_job_12vEDtMQ0mbp1Mo5Z7mzAFQJZazh`. The
# prefix must contain only letters (`[A-Za-z]`), numbers (`[0-9]`),
# underscores (`_`), or dashes (`-`). The maximum length of the entire ID
# is 1,024 characters. If `job_id` is provided, then `prefix` will not
# be used.
# @param [Hash] labels A hash of user-provided labels associated with
# the job. You can use these to organize and group your jobs.
#
# The labels applied to a resource must meet the following requirements:
#
# * Each resource can have multiple labels, up to a maximum of 64.
# * Each label must be a key-value pair.
# * Keys have a minimum length of 1 character and a maximum length of
# 63 characters, and cannot be empty. Values can be empty, and have
# a maximum length of 63 characters.
# * Keys and values can contain only lowercase letters, numeric characters,
# underscores, and dashes. All characters must use UTF-8 encoding, and
# international characters are allowed.
# * The key portion of a label must be unique. However, you can use the
# same key with multiple resources.
# * Keys must start with a lowercase letter or international character.
# @yield [job] a job configuration object
# @yieldparam [Google::Cloud::Bigquery::CopyJob::Updater] job a job
# configuration object for setting additional options.
#
# @return [Google::Cloud::Bigquery::CopyJob]
#
# @example
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
# dataset = bigquery.dataset "my_dataset"
# source_table_id = "bigquery-public-data.samples.shakespeare"
# destination_table = dataset.table "my_destination_table"
#
# copy_job = bigquery.copy_job source_table_id, destination_table
#
# copy_job.wait_until_done!
# copy_job.done? #=> true
#
# @!group Data
#
def copy_job source_table, destination_table, create: nil, write: nil, job_id: nil, prefix: nil, labels: nil
ensure_service!
options = { create: create, write: write, labels: labels, job_id: job_id, prefix: prefix }
updater = CopyJob::Updater.from_options(
service,
Service.get_table_ref(source_table, default_ref: project_ref),
Service.get_table_ref(destination_table, default_ref: project_ref),
options
)
yield updater if block_given?
job_gapi = updater.to_gapi
gapi = service.copy_table job_gapi
Job.from_gapi gapi, service
end
##
# Copies the data from the source table to the destination table using a
# synchronous method that blocks for a response. Timeouts and transient
# errors are generally handled as needed to complete the job. See
# {#copy_job} for the asynchronous version. Use this method instead of
# {Table#copy} to copy from source tables in other projects.
#
# The geographic location for the job ("US", "EU", etc.) can be set via
# {CopyJob::Updater#location=} in a block passed to this method.
#
# @param [String, Table] source_table The source table for the
# copied data. This can be a table object; or a string ID as specified
# by the [Standard SQL Query
# Reference](https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#from-clause)
# (`project-name.dataset_id.table_id`) or the [Legacy SQL Query
# Reference](https://cloud.google.com/bigquery/query-reference#from)
# (`project-name:dataset_id.table_id`).
# @param [String, Table] destination_table The destination table for the
# copied data. This can be a table object; or a string ID as specified
# by the [Standard SQL Query
# Reference](https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#from-clause)
# (`project-name.dataset_id.table_id`) or the [Legacy SQL Query
# Reference](https://cloud.google.com/bigquery/query-reference#from)
# (`project-name:dataset_id.table_id`).
# @param [String] create Specifies whether the job is allowed to create
# new tables. The default value is `needed`.
#
# The following values are supported:
#
# * `needed` - Create the table if it does not exist.
# * `never` - The table must already exist. A 'notFound' error is
# raised if the table does not exist.
# @param [String] write Specifies how to handle data already present in
# the destination table. The default value is `empty`.
#
# The following values are supported:
#
# * `truncate` - BigQuery overwrites the table data.
# * `append` - BigQuery appends the data to the table.
# * `empty` - An error will be returned if the destination table
# already contains data.
# @yield [job] a job configuration object
# @yieldparam [Google::Cloud::Bigquery::CopyJob::Updater] job a job
# configuration object for setting additional options.
#
# @return [Boolean] Returns `true` if the copy operation succeeded.
#
# @example
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
# dataset = bigquery.dataset "my_dataset"
# destination_table = dataset.table "my_destination_table"
#
# bigquery.copy "bigquery-public-data.samples.shakespeare",
# destination_table
#
# @!group Data
#
def copy source_table, destination_table, create: nil, write: nil, &block
job = copy_job source_table, destination_table, create: create, write: write, &block
job.wait_until_done!
ensure_job_succeeded! job
true
end
##
# Queries data by creating a [query
# job](https://cloud.google.com/bigquery/docs/query-overview#query_jobs).
#
# The geographic location for the job ("US", "EU", etc.) can be set via
# {QueryJob::Updater#location=} in a block passed to this method.
#
# @param [String] query A query string, following the BigQuery [query
# syntax](https://cloud.google.com/bigquery/query-reference), of the
# query to execute. Example: "SELECT count(f1) FROM
# [myProjectId:myDatasetId.myTableId]".
# @param [Array, Hash] params Standard SQL only. Used to pass query arguments when the `query` string contains
# either positional (`?`) or named (`@myparam`) query parameters. If value passed is an array `["foo"]`, the
# query must use positional query parameters. If value passed is a hash `{ myparam: "foo" }`, the query must
# use named query parameters. When set, `legacy_sql` will automatically be set to false and `standard_sql` to
# true.
#
# BigQuery types are converted from Ruby types as follows:
#
# | BigQuery | Ruby | Notes |
# |--------------|--------------------------------------|----------------------------------------------------|
# | `BOOL` | `true`/`false` | |
# | `INT64` | `Integer` | |
# | `FLOAT64` | `Float` | |
# | `NUMERIC` | `BigDecimal` | `BigDecimal` values will be rounded to scale 9. |
# | `BIGNUMERIC` | `BigDecimal` | NOT AUTOMATIC: Must be mapped using `types`, below.|
# | `STRING` | `String` | |
# | `DATETIME` | `DateTime` | `DATETIME` does not support time zone. |
# | `DATE` | `Date` | |
# | `GEOGRAPHY` | `String` (WKT or GeoJSON) | NOT AUTOMATIC: Must be mapped using `types`, below.|
# | `TIMESTAMP` | `Time` | |
# | `TIME` | `Google::Cloud::BigQuery::Time` | |
# | `BYTES` | `File`, `IO`, `StringIO`, or similar | |
# | `ARRAY` | `Array` | Nested arrays, `nil` values are not supported. |
# | `STRUCT` | `Hash` | Hash keys may be strings or symbols. |
#
# See [Data Types](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types) for an overview
# of each BigQuery data type, including allowed values. For the `GEOGRAPHY` type, see [Working with BigQuery
# GIS data](https://cloud.google.com/bigquery/docs/gis-data).
# @param [Array, Hash] types Standard SQL only. Types of the SQL parameters in `params`. It is not always
# possible to infer the right SQL type from a value in `params`. In these cases, `types` must be used to
# specify the SQL type for these values.
#
# Arguments must match the value type passed to `params`. This must be an `Array` when the query uses
# positional query parameters. This must be an `Hash` when the query uses named query parameters. The values
# should be BigQuery type codes from the following list:
#
# * `:BOOL`
# * `:INT64`
# * `:FLOAT64`
# * `:NUMERIC`
# * `:BIGNUMERIC`
# * `:STRING`
# * `:DATETIME`
# * `:DATE`
# * `:GEOGRAPHY`
# * `:TIMESTAMP`
# * `:TIME`
# * `:BYTES`
# * `Array` - Lists are specified by providing the type code in an array. For example, an array of integers
# are specified as `[:INT64]`.
# * `Hash` - Types for STRUCT values (`Hash` objects) are specified using a `Hash` object, where the keys
# match the `params` hash, and the values are the types value that matches the data.
#
# Types are optional.
# @param [Hash<String|Symbol, External::DataSource>] external A Hash
# that represents the mapping of the external tables to the table
# names used in the SQL query. The hash keys are the table names, and
# the hash values are the external table objects. See {Project#query}.
# @param [String] priority Specifies a priority for the query. Possible
# values include `INTERACTIVE` and `BATCH`. The default value is
# `INTERACTIVE`.
# @param [Boolean] cache Whether to look for the result in the query
# cache. The query cache is a best-effort cache that will be flushed
# whenever tables in the query are modified. The default value is
# true. For more information, see [query
# caching](https://developers.google.com/bigquery/querying-data).
# @param [Table] table The destination table where the query results
# should be stored. If not present, a new table will be created to
# store the results.
# @param [String] create Specifies whether the job is allowed to create
# new tables. The default value is `needed`.
#
# The following values are supported:
#
# * `needed` - Create the table if it does not exist.
# * `never` - The table must already exist. A 'notFound' error is
# raised if the table does not exist.
# @param [String] write Specifies the action that occurs if the
# destination table already exists. The default value is `empty`.
#
# The following values are supported:
#
# * `truncate` - BigQuery overwrites the table data.
# * `append` - BigQuery appends the data to the table.
# * `empty` - A 'duplicate' error is returned in the job result if the
# table exists and contains data.
# @param [Boolean] dryrun If set to true, BigQuery doesn't run the job.
# Instead, if the query is valid, BigQuery returns statistics about
# the job such as how many bytes would be processed. If the query is
# invalid, an error returns. The default value is false.
# @param [Dataset, String] dataset The default dataset to use for
# unqualified table names in the query. Optional.
# @param [String] project Specifies the default projectId to assume for
# any unqualified table names in the query. Only used if `dataset`
# option is set.
# @param [Boolean] standard_sql Specifies whether to use BigQuery's
# [standard
# SQL](https://cloud.google.com/bigquery/docs/reference/standard-sql/)
# dialect for this query. If set to true, the query will use standard
# SQL rather than the [legacy
# SQL](https://cloud.google.com/bigquery/docs/reference/legacy-sql)
# dialect. Optional. The default value is true.
# @param [Boolean] legacy_sql Specifies whether to use BigQuery's
# [legacy
# SQL](https://cloud.google.com/bigquery/docs/reference/legacy-sql)
# dialect for this query. If set to false, the query will use
# BigQuery's [standard
# SQL](https://cloud.google.com/bigquery/docs/reference/standard-sql/)
# dialect. Optional. The default value is false.
# @param [Boolean] large_results This option is specific to Legacy SQL.
# If `true`, allows the query to produce arbitrarily large result
# tables at a slight cost in performance. Requires `table` parameter
# to be set.
# @param [Boolean] flatten This option is specific to Legacy SQL.
# Flattens all nested and repeated fields in the query results. The
# default value is `true`. `large_results` parameter must be `true` if
# this is set to `false`.
# @param [Integer] maximum_billing_tier Deprecated: Change the billing
# tier to allow high-compute queries.
# @param [Integer] maximum_bytes_billed Limits the bytes billed for this
# job. Queries that will have bytes billed beyond this limit will fail
# (without incurring a charge). Optional. If unspecified, this will be
# set to your project default.
# @param [String] job_id A user-defined ID for the query job. The ID
# must contain only letters (`[A-Za-z]`), numbers (`[0-9]`), underscores
# (`_`), or dashes (`-`). The maximum length is 1,024 characters. If
# `job_id` is provided, then `prefix` will not be used.
#
# See [Generating a job
# ID](https://cloud.google.com/bigquery/docs/managing-jobs#generate-jobid).
# @param [String] prefix A string, usually human-readable, that will be
# prepended to a generated value to produce a unique job ID. For
# example, the prefix `daily_import_job_` can be given to generate a
# job ID such as `daily_import_job_12vEDtMQ0mbp1Mo5Z7mzAFQJZazh`. The
# prefix must contain only letters (`[A-Za-z]`), numbers (`[0-9]`),
# underscores (`_`), or dashes (`-`). The maximum length of the entire ID
# is 1,024 characters. If `job_id` is provided, then `prefix` will not
# be used.
#
# See [Generating a job
# ID](https://cloud.google.com/bigquery/docs/managing-jobs#generate-jobid).
# @param [Hash] labels A hash of user-provided labels associated with
# the job. You can use these to organize and group your jobs.
#
# The labels applied to a resource must meet the following requirements:
#
# * Each resource can have multiple labels, up to a maximum of 64.
# * Each label must be a key-value pair.
# * Keys have a minimum length of 1 character and a maximum length of
# 63 characters, and cannot be empty. Values can be empty, and have
# a maximum length of 63 characters.
# * Keys and values can contain only lowercase letters, numeric characters,
# underscores, and dashes. All characters must use UTF-8 encoding, and
# international characters are allowed.
# * The key portion of a label must be unique. However, you can use the
# same key with multiple resources.
# * Keys must start with a lowercase letter or international character.
# @param [Array<String>, String] udfs User-defined function resources
# used in a legacy SQL query. May be either a code resource to load from
# a Google Cloud Storage URI (`gs://bucket/path`), or an inline resource
# that contains code for a user-defined function (UDF). Providing an
# inline code resource is equivalent to providing a URI for a file
# containing the same code.
#
# This parameter is used for defining User Defined Function (UDF)
# resources only when using legacy SQL. Users of standard SQL should
# leverage either DDL (e.g. `CREATE [TEMPORARY] FUNCTION ...`) or the
# Routines API to define UDF resources.
#
# For additional information on migrating, see: [Migrating to
# standard SQL - Differences in user-defined JavaScript
# functions](https://cloud.google.com/bigquery/docs/reference/standard-sql/migrating-from-legacy-sql#differences_in_user-defined_javascript_functions)
# @param [Boolean] create_session If true, creates a new session, where the
# session ID will be a server generated random id. If false, runs query
# with an existing session ID when one is provided in the `session_id`
# param, otherwise runs query in non-session mode. See {Job#session_id}.
# @param [String] session_id The ID of an existing session. See also the
# `create_session` param and {Job#session_id}.
# @yield [job] a job configuration object
# @yieldparam [Google::Cloud::Bigquery::QueryJob::Updater] job a job
# configuration object for setting query options.
#
# @return [Google::Cloud::Bigquery::QueryJob]
#
# @example Query using standard SQL:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# job = bigquery.query_job "SELECT name FROM " \
# "`my_project.my_dataset.my_table`"
#
# job.wait_until_done!
# if !job.failed?
# job.data.each do |row|
# puts row[:name]
# end
# end
#
# @example Query using legacy SQL:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# job = bigquery.query_job "SELECT name FROM " \
# " [my_project:my_dataset.my_table]",
# legacy_sql: true
#
# job.wait_until_done!
# if !job.failed?
# job.data.each do |row|
# puts row[:name]
# end
# end
#
# @example Query using positional query parameters:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# job = bigquery.query_job "SELECT name FROM " \
# "`my_dataset.my_table` " \
# "WHERE id = ?",
# params: [1]
#
# job.wait_until_done!
# if !job.failed?
# job.data.each do |row|
# puts row[:name]
# end
# end
#
# @example Query using named query parameters:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# job = bigquery.query_job "SELECT name FROM " \
# "`my_dataset.my_table` " \
# "WHERE id = @id",
# params: { id: 1 }
#
# job.wait_until_done!
# if !job.failed?
# job.data.each do |row|
# puts row[:name]
# end
# end
#
# @example Query using named query parameters with types:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# job = bigquery.query_job "SELECT name FROM " \
# "`my_dataset.my_table` " \
# "WHERE id IN UNNEST(@ids)",
# params: { ids: [] },
# types: { ids: [:INT64] }
#
# job.wait_until_done!
# if !job.failed?
# job.data.each do |row|
# puts row[:name]
# end
# end
#
# @example Execute a DDL statement:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# job = bigquery.query_job "CREATE TABLE " \
# "`my_dataset.my_table` " \
# "(x INT64)"
#
# job.wait_until_done!
# if !job.failed?
# table_ref = job.ddl_target_table # Or ddl_target_routine for CREATE/DROP FUNCTION/PROCEDURE
# end
#
# @example Execute a DML statement:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# job = bigquery.query_job "UPDATE " \
# "`my_dataset.my_table` " \
# "SET x = x + 1 " \
# "WHERE x IS NOT NULL"
#
# job.wait_until_done!
# if !job.failed?
# puts job.num_dml_affected_rows
# end
#
# @example Query using external data source, set destination:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# csv_url = "gs://bucket/path/to/data.csv"
# csv_table = bigquery.external csv_url do |csv|
# csv.autodetect = true
# csv.skip_leading_rows = 1
# end
#
# job = bigquery.query_job "SELECT * FROM my_ext_table" do |query|
# query.external = { my_ext_table: csv_table }
# dataset = bigquery.dataset "my_dataset", skip_lookup: true
# query.table = dataset.table "my_table", skip_lookup: true
# end
#
# job.wait_until_done!
# if !job.failed?
# job.data.each do |row|
# puts row[:name]
# end
# end
#
def query_job query,
params: nil,
types: nil,
external: nil,
priority: "INTERACTIVE",
cache: true,
table: nil,
create: nil,
write: nil,
dryrun: nil,
dataset: nil,
project: nil,
standard_sql: nil,
legacy_sql: nil,
large_results: nil,
flatten: nil,
maximum_billing_tier: nil,
maximum_bytes_billed: nil,
job_id: nil,
prefix: nil,
labels: nil,
udfs: nil,
create_session: nil,
session_id: nil
ensure_service!
options = {
params: params,
types: types,
external: external,
priority: priority,
cache: cache,
table: table,
create: create,
write: write,
dryrun: dryrun,
dataset: dataset,
project: (project || self.project),
standard_sql: standard_sql,
legacy_sql: legacy_sql,
large_results: large_results,
flatten: flatten,
maximum_billing_tier: maximum_billing_tier,
maximum_bytes_billed: maximum_bytes_billed,
job_id: job_id,
prefix: prefix,
labels: labels,
udfs: udfs,
create_session: create_session,
session_id: session_id
}
updater = QueryJob::Updater.from_options service, query, options
yield updater if block_given?
gapi = service.query_job updater.to_gapi
Job.from_gapi gapi, service
end
##
# Queries data and waits for the results. In this method, a {QueryJob}
# is created and its results are saved to a temporary table, then read
# from the table. Timeouts and transient errors are generally handled
# as needed to complete the query. When used for executing DDL/DML
# statements, this method does not return row data.
#
# The geographic location for the job ("US", "EU", etc.) can be set via
# {QueryJob::Updater#location=} in a block passed to this method.
#
# @see https://cloud.google.com/bigquery/querying-data Querying Data
#
# @param [String] query A query string, following the BigQuery [query
# syntax](https://cloud.google.com/bigquery/query-reference), of the
# query to execute. Example: "SELECT count(f1) FROM
# [myProjectId:myDatasetId.myTableId]".
# @param [Array, Hash] params Standard SQL only. Used to pass query arguments when the `query` string contains
# either positional (`?`) or named (`@myparam`) query parameters. If value passed is an array `["foo"]`, the
# query must use positional query parameters. If value passed is a hash `{ myparam: "foo" }`, the query must
# use named query parameters. When set, `legacy_sql` will automatically be set to false and `standard_sql` to
# true.
#
# BigQuery types are converted from Ruby types as follows:
#
# | BigQuery | Ruby | Notes |
# |--------------|--------------------------------------|----------------------------------------------------|
# | `BOOL` | `true`/`false` | |
# | `INT64` | `Integer` | |
# | `FLOAT64` | `Float` | |
# | `NUMERIC` | `BigDecimal` | `BigDecimal` values will be rounded to scale 9. |
# | `BIGNUMERIC` | `BigDecimal` | NOT AUTOMATIC: Must be mapped using `types`, below.|
# | `STRING` | `String` | |
# | `DATETIME` | `DateTime` | `DATETIME` does not support time zone. |
# | `DATE` | `Date` | |
# | `GEOGRAPHY` | `String` (WKT or GeoJSON) | NOT AUTOMATIC: Must be mapped using `types`, below.|
# | `TIMESTAMP` | `Time` | |
# | `TIME` | `Google::Cloud::BigQuery::Time` | |
# | `BYTES` | `File`, `IO`, `StringIO`, or similar | |
# | `ARRAY` | `Array` | Nested arrays, `nil` values are not supported. |
# | `STRUCT` | `Hash` | Hash keys may be strings or symbols. |
#
# See [Data Types](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types) for an overview
# of each BigQuery data type, including allowed values. For the `GEOGRAPHY` type, see [Working with BigQuery
# GIS data](https://cloud.google.com/bigquery/docs/gis-data).
# @param [Array, Hash] types Standard SQL only. Types of the SQL parameters in `params`. It is not always
# possible to infer the right SQL type from a value in `params`. In these cases, `types` must be used to
# specify the SQL type for these values.
#
# Arguments must match the value type passed to `params`. This must be an `Array` when the query uses
# positional query parameters. This must be an `Hash` when the query uses named query parameters. The values
# should be BigQuery type codes from the following list:
#
# * `:BOOL`
# * `:INT64`
# * `:FLOAT64`
# * `:NUMERIC`
# * `:BIGNUMERIC`
# * `:STRING`
# * `:DATETIME`
# * `:DATE`
# * `:GEOGRAPHY`
# * `:TIMESTAMP`
# * `:TIME`
# * `:BYTES`
# * `Array` - Lists are specified by providing the type code in an array. For example, an array of integers
# are specified as `[:INT64]`.
# * `Hash` - Types for STRUCT values (`Hash` objects) are specified using a `Hash` object, where the keys
# match the `params` hash, and the values are the types value that matches the data.
#
# Types are optional.
# @param [Hash<String|Symbol, External::DataSource>] external A Hash
# that represents the mapping of the external tables to the table
# names used in the SQL query. The hash keys are the table names, and
# the hash values are the external table objects. See {Project#query}.
# @param [Integer] max The maximum number of rows of data to return per
# page of results. Setting this flag to a small value such as 1000 and
# then paging through results might improve reliability when the query
# result set is large. In addition to this limit, responses are also
# limited to 10 MB. By default, there is no maximum row count, and
# only the byte limit applies.
# @param [Boolean] cache Whether to look for the result in the query
# cache. The query cache is a best-effort cache that will be flushed
# whenever tables in the query are modified. The default value is
# true. For more information, see [query
# caching](https://developers.google.com/bigquery/querying-data).
# @param [String] dataset Specifies the default datasetId and projectId
# to assume for any unqualified table names in the query. If not set,
# all table names in the query string must be qualified in the format
# 'datasetId.tableId'.
# @param [String] project Specifies the default projectId to assume for
# any unqualified table names in the query. Only used if `dataset`
# option is set.
# @param [Boolean] standard_sql Specifies whether to use BigQuery's
# [standard
# SQL](https://cloud.google.com/bigquery/docs/reference/standard-sql/)
# dialect for this query. If set to true, the query will use standard
# SQL rather than the [legacy
# SQL](https://cloud.google.com/bigquery/docs/reference/legacy-sql)
# dialect. When set to true, the values of `large_results` and
# `flatten` are ignored; the query will be run as if `large_results`
# is true and `flatten` is false. Optional. The default value is
# true.
# @param [Boolean] legacy_sql Specifies whether to use BigQuery's
# [legacy
# SQL](https://cloud.google.com/bigquery/docs/reference/legacy-sql)
# dialect for this query. If set to false, the query will use
# BigQuery's [standard
# SQL](https://cloud.google.com/bigquery/docs/reference/standard-sql/)
# When set to false, the values of `large_results` and `flatten` are
# ignored; the query will be run as if `large_results` is true and
# `flatten` is false. Optional. The default value is false.
# @param [String] session_id The ID of an existing session. See the
# `create_session` param in {#query_job} and {Job#session_id}.
# @yield [job] a job configuration object
# @yieldparam [Google::Cloud::Bigquery::QueryJob::Updater] job a job
# configuration object for setting additional options for the query.
#
# @return [Google::Cloud::Bigquery::Data]
#
# @example Query using standard SQL:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# sql = "SELECT name FROM `my_project.my_dataset.my_table`"
# data = bigquery.query sql
#
# # Iterate over the first page of results
# data.each do |row|
# puts row[:name]
# end
# # Retrieve the next page of results
# data = data.next if data.next?
#
# @example Query using legacy SQL:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# sql = "SELECT name FROM [my_project:my_dataset.my_table]"
# data = bigquery.query sql, legacy_sql: true
#
# # Iterate over the first page of results
# data.each do |row|
# puts row[:name]
# end
# # Retrieve the next page of results
# data = data.next if data.next?
#
# @example Retrieve all rows: (See {Data#all})
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# data = bigquery.query "SELECT name FROM `my_dataset.my_table`"
#
# data.all do |row|
# puts row[:name]
# end
#
# @example Query using positional query parameters:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# data = bigquery.query "SELECT name " \
# "FROM `my_dataset.my_table` " \
# "WHERE id = ?",
# params: [1]
#
# # Iterate over the first page of results
# data.each do |row|
# puts row[:name]
# end
# # Retrieve the next page of results
# data = data.next if data.next?
#
# @example Query using named query parameters:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# data = bigquery.query "SELECT name " \
# "FROM `my_dataset.my_table` " \
# "WHERE id = @id",
# params: { id: 1 }
#
# # Iterate over the first page of results
# data.each do |row|
# puts row[:name]
# end
# # Retrieve the next page of results
# data = data.next if data.next?
#
# @example Query using named query parameters with types:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# data = bigquery.query "SELECT name FROM " \
# "`my_dataset.my_table` " \
# "WHERE id IN UNNEST(@ids)",
# params: { ids: [] },
# types: { ids: [:INT64] }
#
# # Iterate over the first page of results
# data.each do |row|
# puts row[:name]
# end
# # Retrieve the next page of results
# data = data.next if data.next?
#
# @example Execute a DDL statement:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# data = bigquery.query "CREATE TABLE `my_dataset.my_table` (x INT64)"
#
# table_ref = data.ddl_target_table # Or ddl_target_routine for CREATE/DROP FUNCTION/PROCEDURE
#
# @example Execute a DML statement:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# data = bigquery.query "UPDATE `my_dataset.my_table` " \
# "SET x = x + 1 " \
# "WHERE x IS NOT NULL"
#
# puts data.num_dml_affected_rows
#
# @example Query using external data source, set destination:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# csv_url = "gs://bucket/path/to/data.csv"
# csv_table = bigquery.external csv_url do |csv|
# csv.autodetect = true
# csv.skip_leading_rows = 1
# end
#
# data = bigquery.query "SELECT * FROM my_ext_table" do |query|
# query.external = { my_ext_table: csv_table }
# dataset = bigquery.dataset "my_dataset", skip_lookup: true
# query.table = dataset.table "my_table", skip_lookup: true
# end
#
# # Iterate over the first page of results
# data.each do |row|
# puts row[:name]
# end
# # Retrieve the next page of results
# data = data.next if data.next?
#
def query query,
params: nil,
types: nil,
external: nil,
max: nil,
cache: true,
dataset: nil,
project: nil,
standard_sql: nil,
legacy_sql: nil,
session_id: nil,
&block
job = query_job query,
params: params,
types: types,
external: external,
cache: cache,
dataset: dataset,
project: project,
standard_sql: standard_sql,
legacy_sql: legacy_sql,
session_id: session_id,
&block
job.wait_until_done!
if job.failed?
begin
# raise to activate ruby exception cause handling
raise job.gapi_error
rescue StandardError => e
# wrap Google::Apis::Error with Google::Cloud::Error
raise Google::Cloud::Error.from_error(e)
end
end
job.data max: max
end
##
# Creates a new External::DataSource (or subclass) object that
# represents the external data source that can be queried from directly,
# even though the data is not stored in BigQuery. Instead of loading or
# streaming the data, this object references the external data source.
#
# @see https://cloud.google.com/bigquery/external-data-sources Querying
# External Data Sources
#
# @param [String, Array<String>] url The fully-qualified URL(s) that
# point to your data in Google Cloud. An attempt will be made to
# derive the format from the URLs provided.
# @param [String|Symbol] format The data format. This value will be used
# even if the provided URLs are recognized as a different format.
# Optional.
#
# The following values are supported:
#
# * `csv` - CSV
# * `json` - [Newline-delimited JSON](http://jsonlines.org/)
# * `avro` - [Avro](http://avro.apache.org/)
# * `sheets` - Google Sheets
# * `datastore_backup` - Cloud Datastore backup
# * `bigtable` - Bigtable
#
# @return [External::DataSource] External data source.
#
# @example
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# csv_url = "gs://bucket/path/to/data.csv"
# csv_table = bigquery.external csv_url do |csv|
# csv.autodetect = true
# csv.skip_leading_rows = 1
# end
#
# data = bigquery.query "SELECT * FROM my_ext_table",
# external: { my_ext_table: csv_table }