We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Support (non-legacy) SQL nested data types
`STRUCT<t>` and `ARRAY<t>` seem to be the types.

See #2342. h/t to @c0b for filing.

---

From #2585: [Sample app that reproduces this](https://github.com/GoogleCloudPlatform/python-docs-samples/blob/176f161cae3d4f01b01456a6e403faf6645414a1/bigquery/cloud-client/simple_app.py)

Stacktrace:

``` python
Traceback (most recent call last):
  File "simple_app.py", line 57, in <module>
    query_shakespeare()
  File "simple_app.py", line 47, in query_shakespeare
    page_token=page_token)
  File "lib/python2.7/site-packages/google/cloud/bigquery/query.py", line 401, in fetch_data
    rows_data = _rows_from_json(response.get('rows', ()), self.schema)
  File "lib/python2.7/site-packages/google/cloud/bigquery/_helpers.py", line 98, in _rows_from_json
    for item in cell['v']])
  File "lib/python2.7/site-packages/google/cloud/bigquery/_helpers.py", line 61, in _record_from_json
    for subfield, cell in zip(field.fields, value['f']):
KeyError: 'f'
```

---

Stepping into the debugger:

``` python
ipdb> value
{u'v': {u'f': [{u'v': u'hamlet'}, {u'v': u'5318'}]}}
ipdb> field.__dict__
{'field_type': u'RECORD', 'description': None, 'name': u'title', 'fields': [<google.cloud.bigquery.schema.SchemaField object at 0x7f4ba9227550>, <google.cloud.bigquery.schema.SchemaField object at 0x7f4ba9227690>], 'mode': u'REPEATED'}
```

(Added by @dhermes)


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `bigquery/google/cloud/bigquery/_helpers.py`
Content:
```
1 # Copyright 2015 Google Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 
15 """Shared helper functions for BigQuery API classes."""
16 
17 from google.cloud._helpers import _datetime_from_microseconds
18 from google.cloud._helpers import _date_from_iso8601_date
19 
20 
21 def _not_null(value, field):
22     """Check whether 'value' should be coerced to 'field' type."""
23     return value is not None or field.mode != 'NULLABLE'
24 
25 
26 def _int_from_json(value, field):
27     """Coerce 'value' to an int, if set or not nullable."""
28     if _not_null(value, field):
29         return int(value)
30 
31 
32 def _float_from_json(value, field):
33     """Coerce 'value' to a float, if set or not nullable."""
34     if _not_null(value, field):
35         return float(value)
36 
37 
38 def _bool_from_json(value, field):
39     """Coerce 'value' to a bool, if set or not nullable."""
40     if _not_null(value, field):
41         return value.lower() in ['t', 'true', '1']
42 
43 
44 def _datetime_from_json(value, field):
45     """Coerce 'value' to a datetime, if set or not nullable."""
46     if _not_null(value, field):
47         # value will be a float in seconds, to microsecond precision, in UTC.
48         return _datetime_from_microseconds(1e6 * float(value))
49 
50 
51 def _date_from_json(value, field):
52     """Coerce 'value' to a datetime date, if set or not nullable"""
53     if _not_null(value, field):
54         return _date_from_iso8601_date(value)
55 
56 
57 def _record_from_json(value, field):
58     """Coerce 'value' to a mapping, if set or not nullable."""
59     if _not_null(value, field):
60         record = {}
61         for subfield, cell in zip(field.fields, value['f']):
62             converter = _CELLDATA_FROM_JSON[subfield.field_type]
63             if field.mode == 'REPEATED':
64                 value = [converter(item, subfield) for item in cell['v']]
65             else:
66                 value = converter(cell['v'], subfield)
67             record[subfield.name] = value
68         return record
69 
70 
71 def _string_from_json(value, _):
72     """NOOP string -> string coercion"""
73     return value
74 
75 
76 _CELLDATA_FROM_JSON = {
77     'INTEGER': _int_from_json,
78     'INT64': _int_from_json,
79     'FLOAT': _float_from_json,
80     'FLOAT64': _float_from_json,
81     'BOOLEAN': _bool_from_json,
82     'BOOL': _bool_from_json,
83     'TIMESTAMP': _datetime_from_json,
84     'DATE': _date_from_json,
85     'RECORD': _record_from_json,
86     'STRING': _string_from_json,
87 }
88 
89 
90 def _row_from_json(row, schema):
91     """Convert JSON row data to row with appropriate types.
92 
93     :type row: dict
94     :param row: A JSON response row to be converted.
95 
96     :type schema: tuple
97     :param schema: A tuple of
98                    :class:`~google.cloud.bigquery.schema.SchemaField`.
99 
100     :rtype: tuple
101     :returns: A tuple of data converted to native types.
102     """
103     row_data = []
104     for field, cell in zip(schema, row['f']):
105         converter = _CELLDATA_FROM_JSON[field.field_type]
106         if field.mode == 'REPEATED':
107             row_data.append([converter(item, field)
108                              for item in cell['v']])
109         else:
110             row_data.append(converter(cell['v'], field))
111 
112     return tuple(row_data)
113 
114 
115 def _rows_from_json(rows, schema):
116     """Convert JSON row data to rows with appropriate types."""
117     return [_row_from_json(row, schema) for row in rows]
118 
119 
120 class _ConfigurationProperty(object):
121     """Base property implementation.
122 
123     Values will be stored on a `_configuration` helper attribute of the
124     property's job instance.
125 
126     :type name: str
127     :param name:  name of the property
128     """
129 
130     def __init__(self, name):
131         self.name = name
132         self._backing_name = '_%s' % (self.name,)
133 
134     def __get__(self, instance, owner):
135         """Descriptor protocal:  accesstor"""
136         if instance is None:
137             return self
138         return getattr(instance._configuration, self._backing_name)
139 
140     def _validate(self, value):
141         """Subclasses override to impose validation policy."""
142         pass
143 
144     def __set__(self, instance, value):
145         """Descriptor protocal:  mutator"""
146         self._validate(value)
147         setattr(instance._configuration, self._backing_name, value)
148 
149     def __delete__(self, instance):
150         """Descriptor protocal:  deleter"""
151         delattr(instance._configuration, self._backing_name)
152 
153 
154 class _TypedProperty(_ConfigurationProperty):
155     """Property implementation:  validates based on value type.
156 
157     :type name: str
158     :param name:  name of the property
159 
160     :type property_type: type or sequence of types
161     :param property_type: type to be validated
162     """
163     def __init__(self, name, property_type):
164         super(_TypedProperty, self).__init__(name)
165         self.property_type = property_type
166 
167     def _validate(self, value):
168         """Ensure that 'value' is of the appropriate type.
169 
170         :raises: ValueError on a type mismatch.
171         """
172         if not isinstance(value, self.property_type):
173             raise ValueError('Required type: %s' % (self.property_type,))
174 
175 
176 class _EnumProperty(_ConfigurationProperty):
177     """Pseudo-enumeration class.
178 
179     Subclasses must define ``ALLOWED`` as a class-level constant:  it must
180     be a sequence of strings.
181 
182     :type name: str
183     :param name:  name of the property.
184     """
185     def _validate(self, value):
186         """Check that ``value`` is one of the allowed values.
187 
188         :raises: ValueError if value is not allowed.
189         """
190         if value not in self.ALLOWED:
191             raise ValueError('Pass one of: %s' ', '.join(self.ALLOWED))
192 
193 
194 class UDFResource(object):
195     """Describe a single user-defined function (UDF) resource.
196 
197     :type udf_type: str
198     :param udf_type: the type of the resource ('inlineCode' or 'resourceUri')
199 
200     :type value: str
201     :param value: the inline code or resource URI.
202 
203     See
204     https://cloud.google.com/bigquery/user-defined-functions#api
205     """
206     def __init__(self, udf_type, value):
207         self.udf_type = udf_type
208         self.value = value
209 
210     def __eq__(self, other):
211         return(
212             self.udf_type == other.udf_type and
213             self.value == other.value)
214 
215 
216 class UDFResourcesProperty(object):
217     """Custom property type, holding :class:`UDFResource` instances."""
218 
219     def __get__(self, instance, owner):
220         """Descriptor protocol:  accessor"""
221         if instance is None:
222             return self
223         return list(instance._udf_resources)
224 
225     def __set__(self, instance, value):
226         """Descriptor protocol:  mutator"""
227         if not all(isinstance(u, UDFResource) for u in value):
228             raise ValueError("udf items must be UDFResource")
229         instance._udf_resources = tuple(value)
230 
231 
232 def _build_udf_resources(resources):
233     """
234     :type resources: sequence of :class:`UDFResource`
235     :param resources: fields to be appended.
236 
237     :rtype: mapping
238     :returns: a mapping describing userDefinedFunctionResources for the query.
239     """
240     udfs = []
241     for resource in resources:
242         udf = {resource.udf_type: resource.value}
243         udfs.append(udf)
244     return udfs
245
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/bigquery/google/cloud/bigquery/_helpers.py b/bigquery/google/cloud/bigquery/_helpers.py
--- a/bigquery/google/cloud/bigquery/_helpers.py
+++ b/bigquery/google/cloud/bigquery/_helpers.py
@@ -58,10 +58,11 @@
     """Coerce 'value' to a mapping, if set or not nullable."""
     if _not_null(value, field):
         record = {}
-        for subfield, cell in zip(field.fields, value['f']):
+        record_iter = zip(field.fields, value['f'])
+        for subfield, cell in record_iter:
             converter = _CELLDATA_FROM_JSON[subfield.field_type]
-            if field.mode == 'REPEATED':
-                value = [converter(item, subfield) for item in cell['v']]
+            if subfield.mode == 'REPEATED':
+                value = [converter(item['v'], subfield) for item in cell['v']]
             else:
                 value = converter(cell['v'], subfield)
             record[subfield.name] = value
@@ -103,7 +104,7 @@
     for field, cell in zip(schema, row['f']):
         converter = _CELLDATA_FROM_JSON[field.field_type]
         if field.mode == 'REPEATED':
-            row_data.append([converter(item, field)
+            row_data.append([converter(item['v'], field)
                              for item in cell['v']])
         else:
             row_data.append(converter(cell['v'], field))

{"golden_diff": "diff --git a/bigquery/google/cloud/bigquery/_helpers.py b/bigquery/google/cloud/bigquery/_helpers.py\n--- a/bigquery/google/cloud/bigquery/_helpers.py\n+++ b/bigquery/google/cloud/bigquery/_helpers.py\n@@ -58,10 +58,11 @@\n     \"\"\"Coerce 'value' to a mapping, if set or not nullable.\"\"\"\n     if _not_null(value, field):\n         record = {}\n-        for subfield, cell in zip(field.fields, value['f']):\n+        record_iter = zip(field.fields, value['f'])\n+        for subfield, cell in record_iter:\n             converter = _CELLDATA_FROM_JSON[subfield.field_type]\n-            if field.mode == 'REPEATED':\n-                value = [converter(item, subfield) for item in cell['v']]\n+            if subfield.mode == 'REPEATED':\n+                value = [converter(item['v'], subfield) for item in cell['v']]\n             else:\n                 value = converter(cell['v'], subfield)\n             record[subfield.name] = value\n@@ -103,7 +104,7 @@\n     for field, cell in zip(schema, row['f']):\n         converter = _CELLDATA_FROM_JSON[field.field_type]\n         if field.mode == 'REPEATED':\n-            row_data.append([converter(item, field)\n+            row_data.append([converter(item['v'], field)\n                              for item in cell['v']])\n         else:\n             row_data.append(converter(cell['v'], field))\n", "issue": "Support (non-legacy) SQL nested data types\n`STRUCT<t>` and `ARRAY<t>` seem to be the types.\n\nSee #2342. h/t to @c0b for filing.\n\n---\n\nFrom #2585: [Sample app that reproduces this](https://github.com/GoogleCloudPlatform/python-docs-samples/blob/176f161cae3d4f01b01456a6e403faf6645414a1/bigquery/cloud-client/simple_app.py)\n\nStacktrace:\n\n``` python\nTraceback (most recent call last):\n  File \"simple_app.py\", line 57, in <module>\n    query_shakespeare()\n  File \"simple_app.py\", line 47, in query_shakespeare\n    page_token=page_token)\n  File \"lib/python2.7/site-packages/google/cloud/bigquery/query.py\", line 401, in fetch_data\n    rows_data = _rows_from_json(response.get('rows', ()), self.schema)\n  File \"lib/python2.7/site-packages/google/cloud/bigquery/_helpers.py\", line 98, in _rows_from_json\n    for item in cell['v']])\n  File \"lib/python2.7/site-packages/google/cloud/bigquery/_helpers.py\", line 61, in _record_from_json\n    for subfield, cell in zip(field.fields, value['f']):\nKeyError: 'f'\n```\n\n---\n\nStepping into the debugger:\n\n``` python\nipdb> value\n{u'v': {u'f': [{u'v': u'hamlet'}, {u'v': u'5318'}]}}\nipdb> field.__dict__\n{'field_type': u'RECORD', 'description': None, 'name': u'title', 'fields': [<google.cloud.bigquery.schema.SchemaField object at 0x7f4ba9227550>, <google.cloud.bigquery.schema.SchemaField object at 0x7f4ba9227690>], 'mode': u'REPEATED'}\n```\n\n(Added by @dhermes)\n\n", "before_files": [{"content": "# Copyright 2015 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Shared helper functions for BigQuery API classes.\"\"\"\n\nfrom google.cloud._helpers import _datetime_from_microseconds\nfrom google.cloud._helpers import _date_from_iso8601_date\n\n\ndef _not_null(value, field):\n    \"\"\"Check whether 'value' should be coerced to 'field' type.\"\"\"\n    return value is not None or field.mode != 'NULLABLE'\n\n\ndef _int_from_json(value, field):\n    \"\"\"Coerce 'value' to an int, if set or not nullable.\"\"\"\n    if _not_null(value, field):\n        return int(value)\n\n\ndef _float_from_json(value, field):\n    \"\"\"Coerce 'value' to a float, if set or not nullable.\"\"\"\n    if _not_null(value, field):\n        return float(value)\n\n\ndef _bool_from_json(value, field):\n    \"\"\"Coerce 'value' to a bool, if set or not nullable.\"\"\"\n    if _not_null(value, field):\n        return value.lower() in ['t', 'true', '1']\n\n\ndef _datetime_from_json(value, field):\n    \"\"\"Coerce 'value' to a datetime, if set or not nullable.\"\"\"\n    if _not_null(value, field):\n        # value will be a float in seconds, to microsecond precision, in UTC.\n        return _datetime_from_microseconds(1e6 * float(value))\n\n\ndef _date_from_json(value, field):\n    \"\"\"Coerce 'value' to a datetime date, if set or not nullable\"\"\"\n    if _not_null(value, field):\n        return _date_from_iso8601_date(value)\n\n\ndef _record_from_json(value, field):\n    \"\"\"Coerce 'value' to a mapping, if set or not nullable.\"\"\"\n    if _not_null(value, field):\n        record = {}\n        for subfield, cell in zip(field.fields, value['f']):\n            converter = _CELLDATA_FROM_JSON[subfield.field_type]\n            if field.mode == 'REPEATED':\n                value = [converter(item, subfield) for item in cell['v']]\n            else:\n                value = converter(cell['v'], subfield)\n            record[subfield.name] = value\n        return record\n\n\ndef _string_from_json(value, _):\n    \"\"\"NOOP string -> string coercion\"\"\"\n    return value\n\n\n_CELLDATA_FROM_JSON = {\n    'INTEGER': _int_from_json,\n    'INT64': _int_from_json,\n    'FLOAT': _float_from_json,\n    'FLOAT64': _float_from_json,\n    'BOOLEAN': _bool_from_json,\n    'BOOL': _bool_from_json,\n    'TIMESTAMP': _datetime_from_json,\n    'DATE': _date_from_json,\n    'RECORD': _record_from_json,\n    'STRING': _string_from_json,\n}\n\n\ndef _row_from_json(row, schema):\n    \"\"\"Convert JSON row data to row with appropriate types.\n\n    :type row: dict\n    :param row: A JSON response row to be converted.\n\n    :type schema: tuple\n    :param schema: A tuple of\n                   :class:`~google.cloud.bigquery.schema.SchemaField`.\n\n    :rtype: tuple\n    :returns: A tuple of data converted to native types.\n    \"\"\"\n    row_data = []\n    for field, cell in zip(schema, row['f']):\n        converter = _CELLDATA_FROM_JSON[field.field_type]\n        if field.mode == 'REPEATED':\n            row_data.append([converter(item, field)\n                             for item in cell['v']])\n        else:\n            row_data.append(converter(cell['v'], field))\n\n    return tuple(row_data)\n\n\ndef _rows_from_json(rows, schema):\n    \"\"\"Convert JSON row data to rows with appropriate types.\"\"\"\n    return [_row_from_json(row, schema) for row in rows]\n\n\nclass _ConfigurationProperty(object):\n    \"\"\"Base property implementation.\n\n    Values will be stored on a `_configuration` helper attribute of the\n    property's job instance.\n\n    :type name: str\n    :param name:  name of the property\n    \"\"\"\n\n    def __init__(self, name):\n        self.name = name\n        self._backing_name = '_%s' % (self.name,)\n\n    def __get__(self, instance, owner):\n        \"\"\"Descriptor protocal:  accesstor\"\"\"\n        if instance is None:\n            return self\n        return getattr(instance._configuration, self._backing_name)\n\n    def _validate(self, value):\n        \"\"\"Subclasses override to impose validation policy.\"\"\"\n        pass\n\n    def __set__(self, instance, value):\n        \"\"\"Descriptor protocal:  mutator\"\"\"\n        self._validate(value)\n        setattr(instance._configuration, self._backing_name, value)\n\n    def __delete__(self, instance):\n        \"\"\"Descriptor protocal:  deleter\"\"\"\n        delattr(instance._configuration, self._backing_name)\n\n\nclass _TypedProperty(_ConfigurationProperty):\n    \"\"\"Property implementation:  validates based on value type.\n\n    :type name: str\n    :param name:  name of the property\n\n    :type property_type: type or sequence of types\n    :param property_type: type to be validated\n    \"\"\"\n    def __init__(self, name, property_type):\n        super(_TypedProperty, self).__init__(name)\n        self.property_type = property_type\n\n    def _validate(self, value):\n        \"\"\"Ensure that 'value' is of the appropriate type.\n\n        :raises: ValueError on a type mismatch.\n        \"\"\"\n        if not isinstance(value, self.property_type):\n            raise ValueError('Required type: %s' % (self.property_type,))\n\n\nclass _EnumProperty(_ConfigurationProperty):\n    \"\"\"Pseudo-enumeration class.\n\n    Subclasses must define ``ALLOWED`` as a class-level constant:  it must\n    be a sequence of strings.\n\n    :type name: str\n    :param name:  name of the property.\n    \"\"\"\n    def _validate(self, value):\n        \"\"\"Check that ``value`` is one of the allowed values.\n\n        :raises: ValueError if value is not allowed.\n        \"\"\"\n        if value not in self.ALLOWED:\n            raise ValueError('Pass one of: %s' ', '.join(self.ALLOWED))\n\n\nclass UDFResource(object):\n    \"\"\"Describe a single user-defined function (UDF) resource.\n\n    :type udf_type: str\n    :param udf_type: the type of the resource ('inlineCode' or 'resourceUri')\n\n    :type value: str\n    :param value: the inline code or resource URI.\n\n    See\n    https://cloud.google.com/bigquery/user-defined-functions#api\n    \"\"\"\n    def __init__(self, udf_type, value):\n        self.udf_type = udf_type\n        self.value = value\n\n    def __eq__(self, other):\n        return(\n            self.udf_type == other.udf_type and\n            self.value == other.value)\n\n\nclass UDFResourcesProperty(object):\n    \"\"\"Custom property type, holding :class:`UDFResource` instances.\"\"\"\n\n    def __get__(self, instance, owner):\n        \"\"\"Descriptor protocol:  accessor\"\"\"\n        if instance is None:\n            return self\n        return list(instance._udf_resources)\n\n    def __set__(self, instance, value):\n        \"\"\"Descriptor protocol:  mutator\"\"\"\n        if not all(isinstance(u, UDFResource) for u in value):\n            raise ValueError(\"udf items must be UDFResource\")\n        instance._udf_resources = tuple(value)\n\n\ndef _build_udf_resources(resources):\n    \"\"\"\n    :type resources: sequence of :class:`UDFResource`\n    :param resources: fields to be appended.\n\n    :rtype: mapping\n    :returns: a mapping describing userDefinedFunctionResources for the query.\n    \"\"\"\n    udfs = []\n    for resource in resources:\n        udf = {resource.udf_type: resource.value}\n        udfs.append(udf)\n    return udfs\n", "path": "bigquery/google/cloud/bigquery/_helpers.py"}], "after_files": [{"content": "# Copyright 2015 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Shared helper functions for BigQuery API classes.\"\"\"\n\nfrom google.cloud._helpers import _datetime_from_microseconds\nfrom google.cloud._helpers import _date_from_iso8601_date\n\n\ndef _not_null(value, field):\n    \"\"\"Check whether 'value' should be coerced to 'field' type.\"\"\"\n    return value is not None or field.mode != 'NULLABLE'\n\n\ndef _int_from_json(value, field):\n    \"\"\"Coerce 'value' to an int, if set or not nullable.\"\"\"\n    if _not_null(value, field):\n        return int(value)\n\n\ndef _float_from_json(value, field):\n    \"\"\"Coerce 'value' to a float, if set or not nullable.\"\"\"\n    if _not_null(value, field):\n        return float(value)\n\n\ndef _bool_from_json(value, field):\n    \"\"\"Coerce 'value' to a bool, if set or not nullable.\"\"\"\n    if _not_null(value, field):\n        return value.lower() in ['t', 'true', '1']\n\n\ndef _datetime_from_json(value, field):\n    \"\"\"Coerce 'value' to a datetime, if set or not nullable.\"\"\"\n    if _not_null(value, field):\n        # value will be a float in seconds, to microsecond precision, in UTC.\n        return _datetime_from_microseconds(1e6 * float(value))\n\n\ndef _date_from_json(value, field):\n    \"\"\"Coerce 'value' to a datetime date, if set or not nullable\"\"\"\n    if _not_null(value, field):\n        return _date_from_iso8601_date(value)\n\n\ndef _record_from_json(value, field):\n    \"\"\"Coerce 'value' to a mapping, if set or not nullable.\"\"\"\n    if _not_null(value, field):\n        record = {}\n        record_iter = zip(field.fields, value['f'])\n        for subfield, cell in record_iter:\n            converter = _CELLDATA_FROM_JSON[subfield.field_type]\n            if subfield.mode == 'REPEATED':\n                value = [converter(item['v'], subfield) for item in cell['v']]\n            else:\n                value = converter(cell['v'], subfield)\n            record[subfield.name] = value\n        return record\n\n\ndef _string_from_json(value, _):\n    \"\"\"NOOP string -> string coercion\"\"\"\n    return value\n\n\n_CELLDATA_FROM_JSON = {\n    'INTEGER': _int_from_json,\n    'INT64': _int_from_json,\n    'FLOAT': _float_from_json,\n    'FLOAT64': _float_from_json,\n    'BOOLEAN': _bool_from_json,\n    'TIMESTAMP': _datetime_from_json,\n    'DATE': _date_from_json,\n    'RECORD': _record_from_json,\n    'STRING': _string_from_json,\n}\n\n\ndef _row_from_json(row, schema):\n    \"\"\"Convert JSON row data to row with appropriate types.\n\n    :type row: dict\n    :param row: A JSON response row to be converted.\n\n    :type schema: tuple\n    :param schema: A tuple of\n                   :class:`~google.cloud.bigquery.schema.SchemaField`.\n\n    :rtype: tuple\n    :returns: A tuple of data converted to native types.\n    \"\"\"\n    row_data = []\n    for field, cell in zip(schema, row['f']):\n        converter = _CELLDATA_FROM_JSON[field.field_type]\n        if field.mode == 'REPEATED':\n            row_data.append([converter(item['v'], field)\n                             for item in cell['v']])\n        else:\n            row_data.append(converter(cell['v'], field))\n\n    return tuple(row_data)\n\n\ndef _rows_from_json(rows, schema):\n    \"\"\"Convert JSON row data to rows with appropriate types.\"\"\"\n    return [_row_from_json(row, schema) for row in rows]\n\n\nclass _ConfigurationProperty(object):\n    \"\"\"Base property implementation.\n\n    Values will be stored on a `_configuration` helper attribute of the\n    property's job instance.\n\n    :type name: str\n    :param name:  name of the property\n    \"\"\"\n\n    def __init__(self, name):\n        self.name = name\n        self._backing_name = '_%s' % (self.name,)\n\n    def __get__(self, instance, owner):\n        \"\"\"Descriptor protocal:  accesstor\"\"\"\n        if instance is None:\n            return self\n        return getattr(instance._configuration, self._backing_name)\n\n    def _validate(self, value):\n        \"\"\"Subclasses override to impose validation policy.\"\"\"\n        pass\n\n    def __set__(self, instance, value):\n        \"\"\"Descriptor protocal:  mutator\"\"\"\n        self._validate(value)\n        setattr(instance._configuration, self._backing_name, value)\n\n    def __delete__(self, instance):\n        \"\"\"Descriptor protocal:  deleter\"\"\"\n        delattr(instance._configuration, self._backing_name)\n\n\nclass _TypedProperty(_ConfigurationProperty):\n    \"\"\"Property implementation:  validates based on value type.\n\n    :type name: str\n    :param name:  name of the property\n\n    :type property_type: type or sequence of types\n    :param property_type: type to be validated\n    \"\"\"\n    def __init__(self, name, property_type):\n        super(_TypedProperty, self).__init__(name)\n        self.property_type = property_type\n\n    def _validate(self, value):\n        \"\"\"Ensure that 'value' is of the appropriate type.\n\n        :raises: ValueError on a type mismatch.\n        \"\"\"\n        if not isinstance(value, self.property_type):\n            raise ValueError('Required type: %s' % (self.property_type,))\n\n\nclass _EnumProperty(_ConfigurationProperty):\n    \"\"\"Pseudo-enumeration class.\n\n    Subclasses must define ``ALLOWED`` as a class-level constant:  it must\n    be a sequence of strings.\n\n    :type name: str\n    :param name:  name of the property.\n    \"\"\"\n    def _validate(self, value):\n        \"\"\"Check that ``value`` is one of the allowed values.\n\n        :raises: ValueError if value is not allowed.\n        \"\"\"\n        if value not in self.ALLOWED:\n            raise ValueError('Pass one of: %s' ', '.join(self.ALLOWED))\n\n\nclass UDFResource(object):\n    \"\"\"Describe a single user-defined function (UDF) resource.\n\n    :type udf_type: str\n    :param udf_type: the type of the resource ('inlineCode' or 'resourceUri')\n\n    :type value: str\n    :param value: the inline code or resource URI.\n\n    See\n    https://cloud.google.com/bigquery/user-defined-functions#api\n    \"\"\"\n    def __init__(self, udf_type, value):\n        self.udf_type = udf_type\n        self.value = value\n\n    def __eq__(self, other):\n        return(\n            self.udf_type == other.udf_type and\n            self.value == other.value)\n\n\nclass UDFResourcesProperty(object):\n    \"\"\"Custom property type, holding :class:`UDFResource` instances.\"\"\"\n\n    def __get__(self, instance, owner):\n        \"\"\"Descriptor protocol:  accessor\"\"\"\n        if instance is None:\n            return self\n        return list(instance._udf_resources)\n\n    def __set__(self, instance, value):\n        \"\"\"Descriptor protocol:  mutator\"\"\"\n        if not all(isinstance(u, UDFResource) for u in value):\n            raise ValueError(\"udf items must be UDFResource\")\n        instance._udf_resources = tuple(value)\n\n\ndef _build_udf_resources(resources):\n    \"\"\"\n    :type resources: sequence of :class:`UDFResource`\n    :param resources: fields to be appended.\n\n    :rtype: mapping\n    :returns: a mapping describing userDefinedFunctionResources for the query.\n    \"\"\"\n    udfs = []\n    for resource in resources:\n        udf = {resource.udf_type: resource.value}\n        udfs.append(udf)\n    return udfs\n", "path": "bigquery/google/cloud/bigquery/_helpers.py"}]}