Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: error using empty array of structs parameter #474

Merged
merged 15 commits into from Feb 24, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
47 changes: 38 additions & 9 deletions google/cloud/bigquery/query.py
Expand Up @@ -186,31 +186,56 @@ class ArrayQueryParameter(_AbstractQueryParameter):

array_type (str):
Name of type of array elements. One of `'STRING'`, `'INT64'`,
`'FLOAT64'`, `'NUMERIC'`, `'BOOL'`, `'TIMESTAMP'`, or `'DATE'`.

values (List[appropriate scalar type]): The parameter array values.
`'FLOAT64'`, `'NUMERIC'`, `'BOOL'`, `'TIMESTAMP'`, `'DATE'`,
or `'STRUCT'`/`'RECORD'`.

values (List[appropriate type]): The parameter array values.

struct_item_type (Optional[google.cloud.bigquery.query.StructQueryParameter]):
plamut marked this conversation as resolved.
Show resolved Hide resolved
The type of array elements. The argument is generally not used, but is
required if ``array_type`` is ``'STRUCT'``/``'RECORD'`` and ``values``
is empty.
This is because the backend requires detailed type information about
array elements, but that cannot be determined for ``'STRUCT'`` items
if there are no elements in the array.
"""

def __init__(self, name, array_type, values):
def __init__(self, name, array_type, values, struct_item_type=None):
self.name = name
self.array_type = array_type
self.values = values

if not values and array_type in {"RECORD", "STRUCT"}:
if struct_item_type is None:
raise ValueError("Missing struct item type info for an empty array.")
self._struct_item_type_api = struct_item_type.to_api_repr()["parameterType"]
else:
self._struct_item_type_api = None # won't be used

@classmethod
def positional(cls, array_type, values):
def positional(cls, array_type, values, struct_item_type=None):
"""Factory for positional parameters.

Args:
array_type (str):
Name of type of array elements. One of `'STRING'`, `'INT64'`,
`'FLOAT64'`, `'NUMERIC'`, `'BOOL'`, `'TIMESTAMP'`, or `'DATE'`.
`'FLOAT64'`, `'NUMERIC'`, `'BOOL'`, `'TIMESTAMP'`, `'DATE'`,
or `'STRUCT'`/`'RECORD'`.

values (List[appropriate scalar type]): The parameter array values.
values (List[appropriate type]): The parameter array values.

struct_item_type (Optional[google.cloud.bigquery.query.StructQueryParameter]):
The type of array elements. The argument is generally not used, but is
required if ``array_type`` is ``'STRUCT'``/``'RECORD'`` and ``values``
is empty.
This is because the backend requires detailed type information about
array elements, but that cannot be determined for ``'STRUCT'`` items
if there are no elements in the array.

Returns:
google.cloud.bigquery.query.ArrayQueryParameter: Instance without name
"""
return cls(None, array_type, values)
return cls(None, array_type, values, struct_item_type=struct_item_type)

@classmethod
def _from_api_repr_struct(cls, resource):
Expand Down Expand Up @@ -265,8 +290,12 @@ def to_api_repr(self):
values = self.values
if self.array_type == "RECORD" or self.array_type == "STRUCT":
reprs = [value.to_api_repr() for value in values]
a_type = reprs[0]["parameterType"]
a_values = [repr_["parameterValue"] for repr_ in reprs]

if reprs:
a_type = reprs[0]["parameterType"]
else:
a_type = self._struct_item_type_api
else:
a_type = {"type": self.array_type}
converter = _SCALAR_VALUE_TO_JSON_PARAM.get(self.array_type)
Expand Down
15 changes: 15 additions & 0 deletions tests/system.py
Expand Up @@ -2203,6 +2203,16 @@ def test_query_w_query_params(self):
characters_param = ArrayQueryParameter(
name=None, array_type="RECORD", values=[phred_param, bharney_param]
)
empty_struct_array_param = ArrayQueryParameter(
name="empty_array_param",
array_type="RECORD",
values=[],
struct_item_type=StructQueryParameter(
None,
ScalarQueryParameter(name="foo", type_="INT64", value=None),
ScalarQueryParameter(name="bar", type_="STRING", value=None),
),
)
hero_param = StructQueryParameter("hero", phred_name_param, phred_age_param)
sidekick_param = StructQueryParameter(
"sidekick", bharney_name_param, bharney_age_param
Expand Down Expand Up @@ -2293,6 +2303,11 @@ def test_query_w_query_params(self):
],
"query_parameters": [characters_param],
},
{
"sql": "SELECT @empty_array_param",
"expected": [],
"query_parameters": [empty_struct_array_param],
},
{
"sql": "SELECT @roles",
"expected": {
Expand Down
29 changes: 29 additions & 0 deletions tests/unit/test_query.py
Expand Up @@ -330,6 +330,10 @@ def test_ctor(self):
self.assertEqual(param.array_type, "INT64")
self.assertEqual(param.values, [1, 2])

def test_ctor_empty_struct_array_wo_type_info(self):
with self.assertRaisesRegex(ValueError, r"(?i)missing.*struct.*type info.*"):
self._make_one(name="foo", array_type="STRUCT", values=[])

def test___eq__(self):
param = self._make_one(name="foo", array_type="INT64", values=[123])
self.assertEqual(param, param)
Expand Down Expand Up @@ -493,6 +497,31 @@ def test_to_api_repr_w_record_type(self):
param = klass.positional(array_type="RECORD", values=[struct])
self.assertEqual(param.to_api_repr(), EXPECTED)

def test_to_api_repr_w_empty_array_of_records_type(self):
from google.cloud.bigquery.query import StructQueryParameter

EXPECTED = {
"parameterType": {
"type": "ARRAY",
"arrayType": {
"type": "STRUCT",
"structTypes": [
{"name": "foo", "type": {"type": "STRING"}},
{"name": "bar", "type": {"type": "INT64"}},
],
},
},
"parameterValue": {"arrayValues": []},
}
one = _make_subparam("foo", "STRING", None)
another = _make_subparam("bar", "INT64", None)
struct = StructQueryParameter.positional(one, another)
klass = self._get_target_class()
param = klass.positional(
array_type="RECORD", values=[], struct_item_type=struct
)
self.assertEqual(param.to_api_repr(), EXPECTED)

def test___eq___wrong_type(self):
field = self._make_one("test", "STRING", ["value"])
other = object()
Expand Down