forked from googleapis/google-cloud-ruby
-
Notifications
You must be signed in to change notification settings - Fork 2
/
dataset.rb
2317 lines (2232 loc) · 98.2 KB
/
dataset.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 "json"
require "google/cloud/errors"
require "google/cloud/bigquery/service"
require "google/cloud/bigquery/table"
require "google/cloud/bigquery/external"
require "google/cloud/bigquery/dataset/list"
require "google/cloud/bigquery/dataset/access"
require "google/cloud/bigquery/convert"
require "google/apis/bigquery_v2"
module Google
module Cloud
module Bigquery
##
# # Dataset
#
# Represents a Dataset. A dataset is a grouping mechanism that holds zero
# or more tables. Datasets are the lowest level unit of access control;
# you cannot control access at the table level. A dataset is contained
# within a specific project.
#
# @example
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# dataset = bigquery.create_dataset "my_dataset",
# name: "My Dataset",
# description: "This is my Dataset"
#
class Dataset
##
# @private The Connection object.
attr_accessor :service
##
# @private The Google API Client object.
attr_accessor :gapi
##
# @private A Google API Client Dataset Reference object.
attr_reader :reference
##
# @private Create an empty Dataset object.
def initialize
@service = nil
@gapi = nil
@reference = nil
end
##
# A unique ID for this dataset, without the project name.
#
# @return [String] The ID must contain only letters (a-z, A-Z), numbers
# (0-9), or underscores (_). The maximum length is 1,024 characters.
#
# @!group Attributes
#
def dataset_id
return reference.dataset_id if reference?
@gapi.dataset_reference.dataset_id
end
##
# The ID of the project containing this dataset.
#
# @return [String] The project ID.
#
# @!group Attributes
#
def project_id
return reference.project_id if reference?
@gapi.dataset_reference.project_id
end
##
# @private
# The gapi fragment containing the Project ID and Dataset ID as a
# camel-cased hash.
def dataset_ref
dataset_ref = reference? ? reference : @gapi.dataset_reference
dataset_ref = dataset_ref.to_h if dataset_ref.respond_to? :to_h
dataset_ref
end
##
# A descriptive name for the dataset.
#
# @return [String, nil] The friendly name, or `nil` if the object is
# a reference (see {#reference?}).
#
# @!group Attributes
#
def name
return nil if reference?
@gapi.friendly_name
end
##
# Updates the descriptive name for the dataset.
#
# If the dataset is not a full resource representation (see
# {#resource_full?}), the full representation will be retrieved before
# the update to comply with ETag-based optimistic concurrency control.
#
# @param [String] new_name The new friendly name, or `nil` if the object
# is a reference (see {#reference?}).
#
# @!group Attributes
#
def name= new_name
reload! unless resource_full?
@gapi.update! friendly_name: new_name
patch_gapi! :friendly_name
end
##
# The ETag hash of the dataset.
#
# @return [String, nil] The ETag hash, or `nil` if the object is a
# reference (see {#reference?}).
#
# @!group Attributes
#
def etag
return nil if reference?
ensure_full_data!
@gapi.etag
end
##
# A URL that can be used to access the dataset using the REST API.
#
# @return [String, nil] A REST URL for the resource, or `nil` if the
# object is a reference (see {#reference?}).
#
# @!group Attributes
#
def api_url
return nil if reference?
ensure_full_data!
@gapi.self_link
end
##
# A user-friendly description of the dataset.
#
# @return [String, nil] The description, or `nil` if the object is a
# reference (see {#reference?}).
#
# @!group Attributes
#
def description
return nil if reference?
ensure_full_data!
@gapi.description
end
##
# Updates the user-friendly description of the dataset.
#
# If the dataset is not a full resource representation (see
# {#resource_full?}), the full representation will be retrieved before
# the update to comply with ETag-based optimistic concurrency control.
#
# @param [String] new_description The new description for the dataset.
#
# @!group Attributes
#
def description= new_description
reload! unless resource_full?
@gapi.update! description: new_description
patch_gapi! :description
end
##
# The default lifetime of all tables in the dataset, in milliseconds.
#
# @return [Integer, nil] The default table expiration in milliseconds,
# or `nil` if not present or the object is a reference (see
# {#reference?}).
#
# @!group Attributes
#
def default_expiration
return nil if reference?
ensure_full_data!
begin
Integer @gapi.default_table_expiration_ms
rescue StandardError
nil
end
end
##
# Updates the default lifetime of all tables in the dataset, in
# milliseconds.
#
# If the dataset is not a full resource representation (see
# {#resource_full?}), the full representation will be retrieved before
# the update to comply with ETag-based optimistic concurrency control.
#
# @param [Integer] new_default_expiration The new default table
# expiration in milliseconds.
#
# @!group Attributes
#
def default_expiration= new_default_expiration
reload! unless resource_full?
@gapi.update! default_table_expiration_ms: new_default_expiration
patch_gapi! :default_table_expiration_ms
end
##
# The time when this dataset was created.
#
# @return [Time, nil] The creation time, or `nil` if not present or the
# object is a reference (see {#reference?}).
#
# @!group Attributes
#
def created_at
return nil if reference?
ensure_full_data!
Convert.millis_to_time @gapi.creation_time
end
##
# The date when this dataset or any of its tables was last modified.
#
# @return [Time, nil] The last modified time, or `nil` if not present or
# the object is a reference (see {#reference?}).
#
# @!group Attributes
#
def modified_at
return nil if reference?
ensure_full_data!
Convert.millis_to_time @gapi.last_modified_time
end
##
# The geographic location where the dataset should reside. Possible
# values include `EU` and `US`. The default value is `US`.
#
# @return [String, nil] The geographic location, or `nil` if the object
# is a reference (see {#reference?}).
#
# @!group Attributes
#
def location
return nil if reference?
ensure_full_data!
@gapi.location
end
##
# A hash of user-provided labels associated with this dataset. Labels
# are used to organize and group datasets. See [Using
# Labels](https://cloud.google.com/bigquery/docs/labels).
#
# The returned hash is frozen and changes are not allowed. Use
# {#labels=} to replace the entire hash.
#
# @return [Hash<String, String>, nil] A hash containing key/value pairs,
# or `nil` if the object is a reference (see {#reference?}).
#
# @example
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
# dataset = bigquery.dataset "my_dataset"
#
# labels = dataset.labels
# labels["department"] #=> "shipping"
#
# @!group Attributes
#
def labels
return nil if reference?
m = @gapi.labels
m = m.to_h if m.respond_to? :to_h
m.dup.freeze
end
##
# Updates the hash of user-provided labels associated with this dataset.
# Labels are used to organize and group datasets. See [Using
# Labels](https://cloud.google.com/bigquery/docs/labels).
#
# If the dataset is not a full resource representation (see
# {#resource_full?}), the full representation will be retrieved before
# the update to comply with ETag-based optimistic concurrency control.
#
# @param [Hash<String, String>] labels A hash containing key/value
# pairs.
#
# * Label keys and values can be no longer than 63 characters.
# * Label keys and values can contain only lowercase letters, numbers,
# underscores, hyphens, and international characters.
# * Label keys and values cannot exceed 128 bytes in size.
# * Label keys must begin with a letter.
# * Label keys must be unique within a dataset.
#
# @example
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
# dataset = bigquery.dataset "my_dataset"
#
# dataset.labels = { "department" => "shipping" }
#
# @!group Attributes
#
def labels= labels
reload! unless resource_full?
@gapi.labels = labels
patch_gapi! :labels
end
##
# Retrieves the access rules for a Dataset. The rules can be updated
# when passing a block, see {Dataset::Access} for all the methods
# available.
#
# If the dataset is not a full resource representation (see
# {#resource_full?}), the full representation will be retrieved before
# the update to comply with ETag-based optimistic concurrency control.
#
# @see https://cloud.google.com/bigquery/access-control BigQuery Access
# Control
#
# @yield [access] a block for setting rules
# @yieldparam [Dataset::Access] access the object accepting rules
#
# @return [Google::Cloud::Bigquery::Dataset::Access] The access object.
#
# @example
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
# dataset = bigquery.dataset "my_dataset"
#
# access = dataset.access
# access.writer_user? "reader@example.com" #=> false
#
# @example Manage the access rules by passing a block:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
# dataset = bigquery.dataset "my_dataset"
#
# dataset.access do |access|
# access.add_owner_group "owners@example.com"
# access.add_writer_user "writer@example.com"
# access.remove_writer_user "readers@example.com"
# access.add_reader_special :all
# access.add_reader_view other_dataset_view_object
# end
#
def access
ensure_full_data!
reload! unless resource_full?
access_builder = Access.from_gapi @gapi
if block_given?
yield access_builder
if access_builder.changed?
@gapi.update! access: access_builder.to_gapi
patch_gapi! :access
end
end
access_builder.freeze
end
##
# Permanently deletes the dataset. The dataset must be empty before it
# can be deleted unless the `force` option is set to `true`.
#
# @param [Boolean] force If `true`, delete all the tables in the
# dataset. If `false` and the dataset contains tables, the request
# will fail. Default is `false`.
#
# @return [Boolean] Returns `true` if the dataset was deleted.
#
# @example
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
# dataset = bigquery.dataset "my_dataset"
#
# dataset.delete
#
# @!group Lifecycle
#
def delete force: nil
ensure_service!
service.delete_dataset dataset_id, force
# Set flag for #exists?
@exists = false
true
end
##
# Creates a new table. If you are adapting existing code that was
# written for the [Rest API
# ](https://cloud.google.com/bigquery/docs/reference/v2/tables#resource),
# you can pass the table's schema as a hash (see example.)
#
# @param [String] table_id The ID of the table. The ID must contain only
# letters (a-z, A-Z), numbers (0-9), or underscores (_). The maximum
# length is 1,024 characters.
# @param [String] name A descriptive name for the table.
# @param [String] description A user-friendly description of the table.
# @yield [table] a block for setting the table
# @yieldparam [Google::Cloud::Bigquery::Table::Updater] table An updater
# to set additional properties on the table in the API request to
# create it.
#
# @return [Google::Cloud::Bigquery::Table] A new table object.
#
# @example
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
# dataset = bigquery.dataset "my_dataset"
#
# table = dataset.create_table "my_table"
#
# @example You can also pass name and description options.
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
# dataset = bigquery.dataset "my_dataset"
#
# table = dataset.create_table "my_table",
# name: "My Table",
# description: "A description of table."
#
# @example Or the table's schema can be configured with the block.
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
# dataset = bigquery.dataset "my_dataset"
#
# table = dataset.create_table "my_table" do |t|
# t.schema.string "first_name", mode: :required
# t.schema.record "cities_lived", mode: :required do |s|
# s.string "place", mode: :required
# s.integer "number_of_years", mode: :required
# end
# end
#
# @example You can define the schema using a nested block.
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
# dataset = bigquery.dataset "my_dataset"
#
# table = dataset.create_table "my_table" do |t|
# t.name = "My Table"
# t.description = "A description of my table."
# t.schema do |s|
# s.string "first_name", mode: :required
# s.record "cities_lived", mode: :repeated do |r|
# r.string "place", mode: :required
# r.integer "number_of_years", mode: :required
# end
# end
# end
#
# @!group Table
#
def create_table table_id, name: nil, description: nil
ensure_service!
new_tb = Google::Apis::BigqueryV2::Table.new(
table_reference: Google::Apis::BigqueryV2::TableReference.new(
project_id: project_id, dataset_id: dataset_id,
table_id: table_id
)
)
updater = Table::Updater.new(new_tb).tap do |tb|
tb.name = name unless name.nil?
tb.description = description unless description.nil?
end
yield updater if block_given?
gapi = service.insert_table dataset_id, updater.to_gapi
Table.from_gapi gapi, service
end
##
# Creates a new [view](https://cloud.google.com/bigquery/docs/views)
# table, which is a virtual table defined by the given SQL query.
#
# BigQuery's views are logical views, not materialized views, which
# means that the query that defines the view is re-executed every time
# the view is queried. Queries are billed according to the total amount
# of data in all table fields referenced directly or indirectly by the
# top-level query. (See {Table#view?} and {Table#query}.)
#
# @param [String] table_id The ID of the view table. The ID must contain
# only letters (a-z, A-Z), numbers (0-9), or underscores (_). The
# maximum length is 1,024 characters.
# @param [String] query The query that BigQuery executes when the view
# is referenced.
# @param [String] name A descriptive name for the table.
# @param [String] description A user-friendly description of the table.
# @param [Boolean] standard_sql Specifies whether to use BigQuery's
# [standard
# SQL](https://cloud.google.com/bigquery/docs/reference/standard-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. Optional. The default value is false.
# @param [Array<String>, String] udfs User-defined function resources
# used in the 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. See [User-Defined
# Functions](https://cloud.google.com/bigquery/docs/reference/standard-sql/user-defined-functions).
#
# @return [Google::Cloud::Bigquery::Table] A new table object.
#
# @example
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
# dataset = bigquery.dataset "my_dataset"
#
# view = dataset.create_view "my_view",
# "SELECT name, age FROM proj.dataset.users"
#
# @example A name and description can be provided:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
# dataset = bigquery.dataset "my_dataset"
#
# view = dataset.create_view "my_view",
# "SELECT name, age FROM proj.dataset.users",
# name: "My View", description: "This is my view"
#
# @!group Table
#
def create_view table_id, query, name: nil, description: nil,
standard_sql: nil, legacy_sql: nil, udfs: nil
use_legacy_sql = Convert.resolve_legacy_sql standard_sql, legacy_sql
new_view_opts = {
table_reference: Google::Apis::BigqueryV2::TableReference.new(
project_id: project_id,
dataset_id: dataset_id,
table_id: table_id
),
friendly_name: name,
description: description,
view: Google::Apis::BigqueryV2::ViewDefinition.new(
query: query,
use_legacy_sql: use_legacy_sql,
user_defined_function_resources: udfs_gapi(udfs)
)
}.delete_if { |_, v| v.nil? }
new_view = Google::Apis::BigqueryV2::Table.new new_view_opts
gapi = service.insert_table dataset_id, new_view
Table.from_gapi gapi, service
end
##
# Retrieves an existing table by ID.
#
# @param [String] table_id The ID of a table.
# @param [Boolean] skip_lookup Optionally create just a local reference
# object without verifying that the resource exists on the BigQuery
# service. Calls made on this object will raise errors if the resource
# does not exist. Default is `false`. Optional.
#
# @return [Google::Cloud::Bigquery::Table, nil] Returns `nil` if the
# table does not exist.
#
# @example
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
# dataset = bigquery.dataset "my_dataset"
#
# table = dataset.table "my_table"
# puts table.name
#
# @example Avoid retrieving the table resource with `skip_lookup`:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# dataset = bigquery.dataset "my_dataset"
#
# table = dataset.table "my_table", skip_lookup: true
#
# @!group Table
#
def table table_id, skip_lookup: nil
ensure_service!
if skip_lookup
return Table.new_reference project_id, dataset_id, table_id, service
end
gapi = service.get_table dataset_id, table_id
Table.from_gapi gapi, service
rescue Google::Cloud::NotFoundError
nil
end
##
# Retrieves the list of tables belonging to the dataset.
#
# @param [String] token A previously-returned page token representing
# part of the larger set of results to view.
# @param [Integer] max Maximum number of tables to return.
#
# @return [Array<Google::Cloud::Bigquery::Table>] An array of tables
# (See {Google::Cloud::Bigquery::Table::List})
#
# @example
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
# dataset = bigquery.dataset "my_dataset"
#
# tables = dataset.tables
# tables.each do |table|
# puts table.name
# end
#
# @example Retrieve all tables: (See {Table::List#all})
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
# dataset = bigquery.dataset "my_dataset"
#
# tables = dataset.tables
# tables.all do |table|
# puts table.name
# end
#
# @!group Table
#
def tables token: nil, max: nil
ensure_service!
options = { token: token, max: max }
gapi = service.list_tables dataset_id, options
Table::List.from_gapi gapi, service, dataset_id, max
end
##
# Queries data by creating a [query
# job](https://cloud.google.com/bigquery/docs/query-overview#query_jobs).
#
# Sets the current dataset as the default dataset in the query. Useful
# for using unqualified table names.
#
# When using standard SQL and passing arguments using `params`, Ruby
# types are mapped to BigQuery types as follows:
#
# | BigQuery | Ruby | Notes |
# |-------------|----------------|---|
# | `BOOL` | `true`/`false` | |
# | `INT64` | `Integer` | |
# | `FLOAT64` | `Float` | |
# | `NUMERIC` | `BigDecimal` | Will be rounded to 9 decimal places |
# | `STRING` | `String` | |
# | `DATETIME` | `DateTime` | `DATETIME` does not support time zone. |
# | `DATE` | `Date` | |
# | `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.
#
# The geographic location for the job ("US", "EU", etc.) can be set via
# {QueryJob::Updater#location=} in a block passed to this method. If the
# dataset is a full resource representation (see {#resource_full?}), the
# location of the job will be automatically set to the location of the
# dataset.
#
# @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.
# @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 {Dataset#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 [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_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-z, A-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-z, A-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. Label
# keys and values can be no longer than 63 characters, can only
# contain lowercase letters, numeric characters, underscores and
# dashes. International characters are allowed. Label values are
# optional. Label keys must start with a letter and each label in the
# list must have a different key. See [Requirements for
# labels](https://cloud.google.com/bigquery/docs/creating-managing-labels#requirements).
# @param [Array<String>, String] udfs User-defined function resources
# used in the 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. See [User-Defined
# Functions](https://cloud.google.com/bigquery/docs/reference/standard-sql/user-defined-functions).
# @param [Integer] maximum_billing_tier Deprecated: Change the billing
# tier to allow high-compute queries.
# @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::QueryJob] A new query job object.
#
# @example Query using standard SQL:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
# dataset = bigquery.dataset "my_dataset"
#
# job = dataset.query_job "SELECT name FROM 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
# dataset = bigquery.dataset "my_dataset"
#
# job = dataset.query_job "SELECT name FROM 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
# dataset = bigquery.dataset "my_dataset"
#
# job = dataset.query_job "SELECT name FROM 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
# dataset = bigquery.dataset "my_dataset"
#
# job = dataset.query_job "SELECT name FROM 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 Execute a DDL statement:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# job = bigquery.query_job "CREATE TABLE my_table (x INT64)"
#
# job.wait_until_done!
# if !job.failed?
# table_ref = job.ddl_target_table
# end
#
# @example Execute a DML statement:
# require "google/cloud/bigquery"
#
# bigquery = Google::Cloud::Bigquery.new
#
# job = bigquery.query_job "UPDATE 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
# dataset = bigquery.dataset "my_dataset"
#
# csv_url = "gs://bucket/path/to/data.csv"
# csv_table = dataset.external csv_url do |csv|
# csv.autodetect = true
# csv.skip_leading_rows = 1
# end
#
# job = dataset.query_job "SELECT * FROM my_ext_table" do |query|
# query.external = { my_ext_table: csv_table }
# 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
#
# @!group Data
#
def query_job query, params: nil, external: nil,
priority: "INTERACTIVE", cache: true, table: nil,
create: nil, write: nil, dryrun: 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
ensure_service!
options = { priority: priority, cache: cache, table: table,
create: create, write: write, dryrun: dryrun,
large_results: large_results, flatten: flatten,
legacy_sql: legacy_sql, standard_sql: standard_sql,
maximum_billing_tier: maximum_billing_tier,
maximum_bytes_billed: maximum_bytes_billed,
job_id: job_id, prefix: prefix, params: params,
external: external, labels: labels, udfs: udfs }
updater = QueryJob::Updater.from_options service, query, options
updater.dataset = self
updater.location = location if location # may be dataset reference
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.
#
# Sets the current dataset as the default dataset in the query. Useful
# for using unqualified table names.
#
# When using standard SQL and passing arguments using `params`, Ruby
# types are mapped to BigQuery types as follows:
#
# | BigQuery | Ruby | Notes |
# |-------------|----------------|---|
# | `BOOL` | `true`/`false` | |
# | `INT64` | `Integer` | |
# | `FLOAT64` | `Float` | |
# | `NUMERIC` | `BigDecimal` | Will be rounded to 9 decimal places |
# | `STRING` | `String` | |
# | `DATETIME` | `DateTime` | `DATETIME` does not support time zone. |
# | `DATE` | `Date` | |
# | `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.
#
# The geographic location for the job ("US", "EU", etc.) can be set via
# {QueryJob::Updater#location=} in a block passed to this method. If the
# dataset is a full resource representation (see {#resource_full?}), the
# location of the job will be automatically set to the location of the
# dataset.
#
# @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