-
Notifications
You must be signed in to change notification settings - Fork 309
/
Copy pathquery.py
1327 lines (1069 loc) · 44.9 KB
/
query.py
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
#
# 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.
"""BigQuery query processing."""
from collections import OrderedDict
import copy
import datetime
import decimal
from typing import Any, Optional, Dict, Union
from google.cloud.bigquery.table import _parse_schema_resource
from google.cloud.bigquery._helpers import _rows_from_json
from google.cloud.bigquery._helpers import _QUERY_PARAMS_FROM_JSON
from google.cloud.bigquery._helpers import _SCALAR_VALUE_TO_JSON_PARAM
from google.cloud.bigquery._helpers import _SUPPORTED_RANGE_ELEMENTS
_SCALAR_VALUE_TYPE = Optional[
Union[str, int, float, decimal.Decimal, bool, datetime.datetime, datetime.date]
]
class ConnectionProperty:
"""A connection-level property to customize query behavior.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/ConnectionProperty
Args:
key:
The key of the property to set, for example, ``'time_zone'`` or
``'session_id'``.
value: The value of the property to set.
"""
def __init__(self, key: str = "", value: str = ""):
self._properties = {
"key": key,
"value": value,
}
@property
def key(self) -> str:
"""Name of the property.
For example:
* ``time_zone``
* ``session_id``
"""
return self._properties["key"]
@property
def value(self) -> str:
"""Value of the property."""
return self._properties["value"]
@classmethod
def from_api_repr(cls, resource) -> "ConnectionProperty":
"""Construct :class:`~google.cloud.bigquery.query.ConnectionProperty`
from JSON resource.
Args:
resource: JSON representation.
Returns:
A connection property.
"""
value = cls()
value._properties = resource
return value
def to_api_repr(self) -> Dict[str, Any]:
"""Construct JSON API representation for the connection property.
Returns:
JSON mapping
"""
return self._properties
class UDFResource(object):
"""Describe a single user-defined function (UDF) resource.
Args:
udf_type (str): The type of the resource ('inlineCode' or 'resourceUri')
value (str): The inline code or resource URI.
See:
https://cloud.google.com/bigquery/user-defined-functions#api
"""
def __init__(self, udf_type, value):
self.udf_type = udf_type
self.value = value
def __eq__(self, other):
if not isinstance(other, UDFResource):
return NotImplemented
return self.udf_type == other.udf_type and self.value == other.value
def __ne__(self, other):
return not self == other
class _AbstractQueryParameterType:
"""Base class for representing query parameter types.
https://cloud.google.com/bigquery/docs/reference/rest/v2/QueryParameter#queryparametertype
"""
@classmethod
def from_api_repr(cls, resource):
"""Factory: construct parameter type from JSON resource.
Args:
resource (Dict): JSON mapping of parameter
Returns:
google.cloud.bigquery.query.QueryParameterType: Instance
"""
raise NotImplementedError
def to_api_repr(self):
"""Construct JSON API representation for the parameter type.
Returns:
Dict: JSON mapping
"""
raise NotImplementedError
class ScalarQueryParameterType(_AbstractQueryParameterType):
"""Type representation for scalar query parameters.
Args:
type_ (str):
One of 'STRING', 'INT64', 'FLOAT64', 'NUMERIC', 'BOOL', 'TIMESTAMP',
'DATETIME', or 'DATE'.
name (Optional[str]):
The name of the query parameter. Primarily used if the type is
one of the subfields in ``StructQueryParameterType`` instance.
description (Optional[str]):
The query parameter description. Primarily used if the type is
one of the subfields in ``StructQueryParameterType`` instance.
"""
def __init__(self, type_, *, name=None, description=None):
self._type = type_
self.name = name
self.description = description
@classmethod
def from_api_repr(cls, resource):
"""Factory: construct parameter type from JSON resource.
Args:
resource (Dict): JSON mapping of parameter
Returns:
google.cloud.bigquery.query.ScalarQueryParameterType: Instance
"""
type_ = resource["type"]
return cls(type_)
def to_api_repr(self):
"""Construct JSON API representation for the parameter type.
Returns:
Dict: JSON mapping
"""
# Name and description are only used if the type is a field inside a struct
# type, but it's StructQueryParameterType's responsibilty to use these two
# attributes in the API representation when needed. Here we omit them.
return {"type": self._type}
def with_name(self, new_name: Union[str, None]):
"""Return a copy of the instance with ``name`` set to ``new_name``.
Args:
name (Union[str, None]):
The new name of the query parameter type. If ``None``, the existing
name is cleared.
Returns:
google.cloud.bigquery.query.ScalarQueryParameterType:
A new instance with updated name.
"""
return type(self)(self._type, name=new_name, description=self.description)
def __repr__(self):
name = f", name={self.name!r}" if self.name is not None else ""
description = (
f", description={self.description!r}"
if self.description is not None
else ""
)
return f"{self.__class__.__name__}({self._type!r}{name}{description})"
class ArrayQueryParameterType(_AbstractQueryParameterType):
"""Type representation for array query parameters.
Args:
array_type (Union[ScalarQueryParameterType, StructQueryParameterType]):
The type of array elements.
name (Optional[str]):
The name of the query parameter. Primarily used if the type is
one of the subfields in ``StructQueryParameterType`` instance.
description (Optional[str]):
The query parameter description. Primarily used if the type is
one of the subfields in ``StructQueryParameterType`` instance.
"""
def __init__(self, array_type, *, name=None, description=None):
self._array_type = array_type
self.name = name
self.description = description
@classmethod
def from_api_repr(cls, resource):
"""Factory: construct parameter type from JSON resource.
Args:
resource (Dict): JSON mapping of parameter
Returns:
google.cloud.bigquery.query.ArrayQueryParameterType: Instance
"""
array_item_type = resource["arrayType"]["type"]
if array_item_type in {"STRUCT", "RECORD"}:
klass = StructQueryParameterType
else:
klass = ScalarQueryParameterType
item_type_instance = klass.from_api_repr(resource["arrayType"])
return cls(item_type_instance)
def to_api_repr(self):
"""Construct JSON API representation for the parameter type.
Returns:
Dict: JSON mapping
"""
# Name and description are only used if the type is a field inside a struct
# type, but it's StructQueryParameterType's responsibilty to use these two
# attributes in the API representation when needed. Here we omit them.
return {
"type": "ARRAY",
"arrayType": self._array_type.to_api_repr(),
}
def __repr__(self):
name = f", name={self.name!r}" if self.name is not None else ""
description = (
f", description={self.description!r}"
if self.description is not None
else ""
)
return f"{self.__class__.__name__}({self._array_type!r}{name}{description})"
class StructQueryParameterType(_AbstractQueryParameterType):
"""Type representation for struct query parameters.
Args:
fields (Iterable[Union[ \
ArrayQueryParameterType, ScalarQueryParameterType, StructQueryParameterType \
]]):
An non-empty iterable describing the struct's field types.
name (Optional[str]):
The name of the query parameter. Primarily used if the type is
one of the subfields in ``StructQueryParameterType`` instance.
description (Optional[str]):
The query parameter description. Primarily used if the type is
one of the subfields in ``StructQueryParameterType`` instance.
"""
def __init__(self, *fields, name=None, description=None):
if not fields:
raise ValueError("Struct type must have at least one field defined.")
self._fields = fields # fields is a tuple (immutable), no shallow copy needed
self.name = name
self.description = description
@property
def fields(self):
return self._fields # no copy needed, self._fields is an immutable sequence
@classmethod
def from_api_repr(cls, resource):
"""Factory: construct parameter type from JSON resource.
Args:
resource (Dict): JSON mapping of parameter
Returns:
google.cloud.bigquery.query.StructQueryParameterType: Instance
"""
fields = []
for struct_field in resource["structTypes"]:
type_repr = struct_field["type"]
if type_repr["type"] in {"STRUCT", "RECORD"}:
klass = StructQueryParameterType
elif type_repr["type"] == "ARRAY":
klass = ArrayQueryParameterType
else:
klass = ScalarQueryParameterType
type_instance = klass.from_api_repr(type_repr)
type_instance.name = struct_field.get("name")
type_instance.description = struct_field.get("description")
fields.append(type_instance)
return cls(*fields)
def to_api_repr(self):
"""Construct JSON API representation for the parameter type.
Returns:
Dict: JSON mapping
"""
fields = []
for field in self._fields:
item = {"type": field.to_api_repr()}
if field.name is not None:
item["name"] = field.name
if field.description is not None:
item["description"] = field.description
fields.append(item)
return {
"type": "STRUCT",
"structTypes": fields,
}
def __repr__(self):
name = f", name={self.name!r}" if self.name is not None else ""
description = (
f", description={self.description!r}"
if self.description is not None
else ""
)
items = ", ".join(repr(field) for field in self._fields)
return f"{self.__class__.__name__}({items}{name}{description})"
class RangeQueryParameterType(_AbstractQueryParameterType):
"""Type representation for range query parameters.
Args:
type_ (Union[ScalarQueryParameterType, str]):
Type of range element, must be one of 'TIMESTAMP', 'DATETIME', or
'DATE'.
name (Optional[str]):
The name of the query parameter. Primarily used if the type is
one of the subfields in ``StructQueryParameterType`` instance.
description (Optional[str]):
The query parameter description. Primarily used if the type is
one of the subfields in ``StructQueryParameterType`` instance.
"""
@classmethod
def _parse_range_element_type(self, type_):
"""Helper method that parses the input range element type, which may
be a string, or a ScalarQueryParameterType object.
Returns:
google.cloud.bigquery.query.ScalarQueryParameterType: Instance
"""
if isinstance(type_, str):
if type_ not in _SUPPORTED_RANGE_ELEMENTS:
raise ValueError(
"If given as a string, range element type must be one of "
"'TIMESTAMP', 'DATE', or 'DATETIME'."
)
return ScalarQueryParameterType(type_)
elif isinstance(type_, ScalarQueryParameterType):
if type_._type not in _SUPPORTED_RANGE_ELEMENTS:
raise ValueError(
"If given as a ScalarQueryParameter object, range element "
"type must be one of 'TIMESTAMP', 'DATE', or 'DATETIME' "
"type."
)
return type_
else:
raise ValueError(
"range_type must be a string or ScalarQueryParameter object, "
"of 'TIMESTAMP', 'DATE', or 'DATETIME' type."
)
def __init__(self, type_, *, name=None, description=None):
self.type_ = self._parse_range_element_type(type_)
self.name = name
self.description = description
@classmethod
def from_api_repr(cls, resource):
"""Factory: construct parameter type from JSON resource.
Args:
resource (Dict): JSON mapping of parameter
Returns:
google.cloud.bigquery.query.RangeQueryParameterType: Instance
"""
type_ = resource["rangeElementType"]["type"]
name = resource.get("name")
description = resource.get("description")
return cls(type_, name=name, description=description)
def to_api_repr(self):
"""Construct JSON API representation for the parameter type.
Returns:
Dict: JSON mapping
"""
# Name and description are only used if the type is a field inside a struct
# type, but it's StructQueryParameterType's responsibilty to use these two
# attributes in the API representation when needed. Here we omit them.
return {
"type": "RANGE",
"rangeElementType": self.type_.to_api_repr(),
}
def with_name(self, new_name: Union[str, None]):
"""Return a copy of the instance with ``name`` set to ``new_name``.
Args:
name (Union[str, None]):
The new name of the range query parameter type. If ``None``,
the existing name is cleared.
Returns:
google.cloud.bigquery.query.RangeQueryParameterType:
A new instance with updated name.
"""
return type(self)(self.type_, name=new_name, description=self.description)
def __repr__(self):
name = f", name={self.name!r}" if self.name is not None else ""
description = (
f", description={self.description!r}"
if self.description is not None
else ""
)
return f"{self.__class__.__name__}({self.type_!r}{name}{description})"
def _key(self):
"""A tuple key that uniquely describes this field.
Used to compute this instance's hashcode and evaluate equality.
Returns:
Tuple: The contents of this
:class:`~google.cloud.bigquery.query.RangeQueryParameterType`.
"""
type_ = self.type_.to_api_repr()
return (self.name, type_, self.description)
def __eq__(self, other):
if not isinstance(other, RangeQueryParameterType):
return NotImplemented
return self._key() == other._key()
def __ne__(self, other):
return not self == other
class _AbstractQueryParameter(object):
"""Base class for named / positional query parameters."""
@classmethod
def from_api_repr(cls, resource: dict) -> "_AbstractQueryParameter":
"""Factory: construct parameter from JSON resource.
Args:
resource (Dict): JSON mapping of parameter
Returns:
A new instance of _AbstractQueryParameter subclass.
"""
raise NotImplementedError
def to_api_repr(self) -> dict:
"""Construct JSON API representation for the parameter.
Returns:
Dict: JSON representation for the parameter.
"""
raise NotImplementedError
class ScalarQueryParameter(_AbstractQueryParameter):
"""Named / positional query parameters for scalar values.
Args:
name:
Parameter name, used via ``@foo`` syntax. If None, the
parameter can only be addressed via position (``?``).
type_:
Name of parameter type. See
:class:`google.cloud.bigquery.enums.SqlTypeNames` and
:class:`google.cloud.bigquery.query.SqlParameterScalarTypes` for
supported types.
value:
The scalar parameter value.
"""
def __init__(
self,
name: Optional[str],
type_: Optional[Union[str, ScalarQueryParameterType]],
value: _SCALAR_VALUE_TYPE,
):
self.name = name
if isinstance(type_, ScalarQueryParameterType):
self.type_ = type_._type
else:
self.type_ = type_
self.value = value
@classmethod
def positional(
cls, type_: Union[str, ScalarQueryParameterType], value: _SCALAR_VALUE_TYPE
) -> "ScalarQueryParameter":
"""Factory for positional paramater.
Args:
type_:
Name of parameter type. One of 'STRING', 'INT64',
'FLOAT64', 'NUMERIC', 'BIGNUMERIC', 'BOOL', 'TIMESTAMP', 'DATETIME', or
'DATE'.
value:
The scalar parameter value.
Returns:
google.cloud.bigquery.query.ScalarQueryParameter: Instance without name
"""
return cls(None, type_, value)
@classmethod
def from_api_repr(cls, resource: dict) -> "ScalarQueryParameter":
"""Factory: construct parameter from JSON resource.
Args:
resource (Dict): JSON mapping of parameter
Returns:
google.cloud.bigquery.query.ScalarQueryParameter: Instance
"""
name = resource.get("name")
type_ = resource["parameterType"]["type"]
# parameterValue might not be present if JSON resource originates
# from the back-end - the latter omits it for None values.
value = resource.get("parameterValue", {}).get("value")
if value is not None:
converted = _QUERY_PARAMS_FROM_JSON[type_](value, None)
else:
converted = None
return cls(name, type_, converted)
def to_api_repr(self) -> dict:
"""Construct JSON API representation for the parameter.
Returns:
Dict: JSON mapping
"""
value = self.value
converter = _SCALAR_VALUE_TO_JSON_PARAM.get(self.type_, lambda value: value)
value = converter(value) # type: ignore
resource: Dict[str, Any] = {
"parameterType": {"type": self.type_},
"parameterValue": {"value": value},
}
if self.name is not None:
resource["name"] = self.name
return resource
def _key(self):
"""A tuple key that uniquely describes this field.
Used to compute this instance's hashcode and evaluate equality.
Returns:
Tuple: The contents of this :class:`~google.cloud.bigquery.query.ScalarQueryParameter`.
"""
return (self.name, self.type_.upper(), self.value)
def __eq__(self, other):
if not isinstance(other, ScalarQueryParameter):
return NotImplemented
return self._key() == other._key()
def __ne__(self, other):
return not self == other
def __repr__(self):
return "ScalarQueryParameter{}".format(self._key())
class ArrayQueryParameter(_AbstractQueryParameter):
"""Named / positional query parameters for array values.
Args:
name (Optional[str]):
Parameter name, used via ``@foo`` syntax. If None, the
parameter can only be addressed via position (``?``).
array_type (Union[str, ScalarQueryParameterType, StructQueryParameterType]):
The type of array elements. If given as a string, it must be one of
`'STRING'`, `'INT64'`, `'FLOAT64'`, `'NUMERIC'`, `'BIGNUMERIC'`, `'BOOL'`,
`'TIMESTAMP'`, `'DATE'`, or `'STRUCT'`/`'RECORD'`.
If the type is ``'STRUCT'``/``'RECORD'`` and ``values`` is empty,
the exact item type cannot be deduced, thus a ``StructQueryParameterType``
instance needs to be passed in.
values (List[appropriate type]): The parameter array values.
"""
def __init__(self, name, array_type, values) -> None:
self.name = name
self.values = values
if isinstance(array_type, str):
if not values and array_type in {"RECORD", "STRUCT"}:
raise ValueError(
"Missing detailed struct item type info for an empty array, "
"please provide a StructQueryParameterType instance."
)
self.array_type = array_type
@classmethod
def positional(cls, array_type: str, values: list) -> "ArrayQueryParameter":
"""Factory for positional parameters.
Args:
array_type (Union[str, ScalarQueryParameterType, StructQueryParameterType]):
The type of array elements. If given as a string, it must be one of
`'STRING'`, `'INT64'`, `'FLOAT64'`, `'NUMERIC'`, `'BIGNUMERIC'`,
`'BOOL'`, `'TIMESTAMP'`, `'DATE'`, or `'STRUCT'`/`'RECORD'`.
If the type is ``'STRUCT'``/``'RECORD'`` and ``values`` is empty,
the exact item type cannot be deduced, thus a ``StructQueryParameterType``
instance needs to be passed in.
values (List[appropriate type]): The parameter array values.
Returns:
google.cloud.bigquery.query.ArrayQueryParameter: Instance without name
"""
return cls(None, array_type, values)
@classmethod
def _from_api_repr_struct(cls, resource):
name = resource.get("name")
converted = []
# We need to flatten the array to use the StructQueryParameter
# parse code.
resource_template = {
# The arrayType includes all the types of the fields of the STRUCT
"parameterType": resource["parameterType"]["arrayType"]
}
for array_value in resource["parameterValue"]["arrayValues"]:
struct_resource = copy.deepcopy(resource_template)
struct_resource["parameterValue"] = array_value
struct_value = StructQueryParameter.from_api_repr(struct_resource)
converted.append(struct_value)
return cls(name, "STRUCT", converted)
@classmethod
def _from_api_repr_scalar(cls, resource):
name = resource.get("name")
array_type = resource["parameterType"]["arrayType"]["type"]
parameter_value = resource.get("parameterValue", {})
array_values = parameter_value.get("arrayValues", ())
values = [value["value"] for value in array_values]
converted = [
_QUERY_PARAMS_FROM_JSON[array_type](value, None) for value in values
]
return cls(name, array_type, converted)
@classmethod
def from_api_repr(cls, resource: dict) -> "ArrayQueryParameter":
"""Factory: construct parameter from JSON resource.
Args:
resource (Dict): JSON mapping of parameter
Returns:
google.cloud.bigquery.query.ArrayQueryParameter: Instance
"""
array_type = resource["parameterType"]["arrayType"]["type"]
if array_type == "STRUCT":
return cls._from_api_repr_struct(resource)
return cls._from_api_repr_scalar(resource)
def to_api_repr(self) -> dict:
"""Construct JSON API representation for the parameter.
Returns:
Dict: JSON mapping
"""
values = self.values
if self.array_type in {"RECORD", "STRUCT"} or isinstance(
self.array_type, StructQueryParameterType
):
reprs = [value.to_api_repr() for value in values]
a_values = [repr_["parameterValue"] for repr_ in reprs]
if reprs:
a_type = reprs[0]["parameterType"]
else:
# This assertion always evaluates to True because the
# constructor disallows STRUCT/RECORD type defined as a
# string with empty values.
assert isinstance(self.array_type, StructQueryParameterType)
a_type = self.array_type.to_api_repr()
else:
# Scalar array item type.
if isinstance(self.array_type, str):
a_type = {"type": self.array_type}
else:
a_type = self.array_type.to_api_repr()
converter = _SCALAR_VALUE_TO_JSON_PARAM.get(
a_type["type"], lambda value: value
)
values = [converter(value) for value in values] # type: ignore
a_values = [{"value": value} for value in values]
resource = {
"parameterType": {"type": "ARRAY", "arrayType": a_type},
"parameterValue": {"arrayValues": a_values},
}
if self.name is not None:
resource["name"] = self.name
return resource
def _key(self):
"""A tuple key that uniquely describes this field.
Used to compute this instance's hashcode and evaluate equality.
Returns:
Tuple: The contents of this :class:`~google.cloud.bigquery.query.ArrayQueryParameter`.
"""
if isinstance(self.array_type, str):
item_type = self.array_type
elif isinstance(self.array_type, ScalarQueryParameterType):
item_type = self.array_type._type
else:
item_type = "STRUCT"
return (self.name, item_type.upper(), self.values)
def __eq__(self, other):
if not isinstance(other, ArrayQueryParameter):
return NotImplemented
return self._key() == other._key()
def __ne__(self, other):
return not self == other
def __repr__(self):
return "ArrayQueryParameter{}".format(self._key())
class StructQueryParameter(_AbstractQueryParameter):
"""Name / positional query parameters for struct values.
Args:
name (Optional[str]):
Parameter name, used via ``@foo`` syntax. If None, the
parameter can only be addressed via position (``?``).
sub_params (Union[Tuple[
google.cloud.bigquery.query.ScalarQueryParameter,
google.cloud.bigquery.query.ArrayQueryParameter,
google.cloud.bigquery.query.StructQueryParameter
]]): The sub-parameters for the struct
"""
def __init__(self, name, *sub_params) -> None:
self.name = name
self.struct_types: Dict[str, Any] = OrderedDict()
self.struct_values: Dict[str, Any] = {}
types = self.struct_types
values = self.struct_values
for sub in sub_params:
if isinstance(sub, self.__class__):
types[sub.name] = "STRUCT"
values[sub.name] = sub
elif isinstance(sub, ArrayQueryParameter):
types[sub.name] = "ARRAY"
values[sub.name] = sub
else:
types[sub.name] = sub.type_
values[sub.name] = sub.value
@classmethod
def positional(cls, *sub_params):
"""Factory for positional parameters.
Args:
sub_params (Union[Tuple[
google.cloud.bigquery.query.ScalarQueryParameter,
google.cloud.bigquery.query.ArrayQueryParameter,
google.cloud.bigquery.query.StructQueryParameter
]]): The sub-parameters for the struct
Returns:
google.cloud.bigquery.query.StructQueryParameter: Instance without name
"""
return cls(None, *sub_params)
@classmethod
def from_api_repr(cls, resource: dict) -> "StructQueryParameter":
"""Factory: construct parameter from JSON resource.
Args:
resource (Dict): JSON mapping of parameter
Returns:
google.cloud.bigquery.query.StructQueryParameter: Instance
"""
name = resource.get("name")
instance = cls(name)
type_resources = {}
types = instance.struct_types
for item in resource["parameterType"]["structTypes"]:
types[item["name"]] = item["type"]["type"]
type_resources[item["name"]] = item["type"]
struct_values = resource["parameterValue"]["structValues"]
for key, value in struct_values.items():
type_ = types[key]
converted: Optional[Union[ArrayQueryParameter, StructQueryParameter]] = None
if type_ == "STRUCT":
struct_resource = {
"name": key,
"parameterType": type_resources[key],
"parameterValue": value,
}
converted = StructQueryParameter.from_api_repr(struct_resource)
elif type_ == "ARRAY":
struct_resource = {
"name": key,
"parameterType": type_resources[key],
"parameterValue": value,
}
converted = ArrayQueryParameter.from_api_repr(struct_resource)
else:
value = value["value"]
converted = _QUERY_PARAMS_FROM_JSON[type_](value, None)
instance.struct_values[key] = converted
return instance
def to_api_repr(self) -> dict:
"""Construct JSON API representation for the parameter.
Returns:
Dict: JSON mapping
"""
s_types = {}
values = {}
for name, value in self.struct_values.items():
type_ = self.struct_types[name]
if type_ in ("STRUCT", "ARRAY"):
repr_ = value.to_api_repr()
s_types[name] = {"name": name, "type": repr_["parameterType"]}
values[name] = repr_["parameterValue"]
else:
s_types[name] = {"name": name, "type": {"type": type_}}
converter = _SCALAR_VALUE_TO_JSON_PARAM.get(type_, lambda value: value)
values[name] = {"value": converter(value)}
resource = {
"parameterType": {
"type": "STRUCT",
"structTypes": [s_types[key] for key in self.struct_types],
},
"parameterValue": {"structValues": values},
}
if self.name is not None:
resource["name"] = self.name
return resource
def _key(self):
"""A tuple key that uniquely describes this field.
Used to compute this instance's hashcode and evaluate equality.
Returns:
Tuple: The contents of this :class:`~google.cloud.bigquery.ArrayQueryParameter`.
"""
return (self.name, self.struct_types, self.struct_values)
def __eq__(self, other):
if not isinstance(other, StructQueryParameter):
return NotImplemented
return self._key() == other._key()
def __ne__(self, other):
return not self == other
def __repr__(self):
return "StructQueryParameter{}".format(self._key())
class RangeQueryParameter(_AbstractQueryParameter):
"""Named / positional query parameters for range values.
Args:
range_element_type (Union[str, RangeQueryParameterType]):
The type of range elements. It must be one of 'TIMESTAMP',
'DATE', or 'DATETIME'.
start (Optional[Union[ScalarQueryParameter, str]]):
The start of the range value. Must be the same type as
range_element_type. If not provided, it's interpreted as UNBOUNDED.
end (Optional[Union[ScalarQueryParameter, str]]):
The end of the range value. Must be the same type as
range_element_type. If not provided, it's interpreted as UNBOUNDED.
name (Optional[str]):
Parameter name, used via ``@foo`` syntax. If None, the
parameter can only be addressed via position (``?``).
"""
@classmethod
def _parse_range_element_type(self, range_element_type):
if isinstance(range_element_type, str):
if range_element_type not in _SUPPORTED_RANGE_ELEMENTS:
raise ValueError(
"If given as a string, range_element_type must be one of "
f"'TIMESTAMP', 'DATE', or 'DATETIME'. Got {range_element_type}."
)
return RangeQueryParameterType(range_element_type)
elif isinstance(range_element_type, RangeQueryParameterType):
if range_element_type.type_._type not in _SUPPORTED_RANGE_ELEMENTS:
raise ValueError(
"If given as a RangeQueryParameterType object, "
"range_element_type must be one of 'TIMESTAMP', 'DATE', "
"or 'DATETIME' type."
)
return range_element_type
else:
raise ValueError(
"range_element_type must be a string or "
"RangeQueryParameterType object, of 'TIMESTAMP', 'DATE', "
"or 'DATETIME' type. Got "
f"{type(range_element_type)}:{range_element_type}"
)
@classmethod
def _serialize_range_element_value(self, value, type_):
if value is None or isinstance(value, str):
return value
else:
converter = _SCALAR_VALUE_TO_JSON_PARAM.get(type_)
if converter is not None:
return converter(value) # type: ignore
else:
raise ValueError(
f"Cannot convert range element value from type {type_}, "
"must be one of the strings 'TIMESTAMP', 'DATE' "
"'DATETIME' or a RangeQueryParameterType object."
)
def __init__(
self,
range_element_type,
start=None,