GeezerVison is showing github.com — feat: support RANGE in queries Part 2: Arrow (#1868) · chenhance/python-bigquery@5251b5d
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: google/cloud/bigquery/_helpers.py +7-9Lines changed: 7 additions & 9 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 66 | 66 | _UNIVERSE_DOMAIN_ENV = "GOOGLE_CLOUD_UNIVERSE_DOMAIN" | 67 | 67 | """Environment variable for setting universe domain.""" | 68 | 68 |
| | 69 | +_SUPPORTED_RANGE_ELEMENTS = {"TIMESTAMP", "DATETIME", "DATE"} | | 70 | + | 69 | 71 |
| 70 | 72 | def _get_client_universe( | 71 | 73 | client_options: Optional[Union[client_options_lib.ClientOptions, dict]] | @@ -310,17 +312,13 @@ def _json_from_json(value, field): | 310 | 312 |
| 311 | 313 |
| 312 | 314 | def _range_element_from_json(value, field): | 313 | | - """Coerce 'value' to a range element value, if set or not nullable.""" | | 315 | + """Coerce 'value' to a range element value.""" | 314 | 316 | if value == "UNBOUNDED": | 315 | 317 | return None | 316 | | - elif field.element_type == "DATE": | 317 | | - return _date_from_json(value, None) | 318 | | - elif field.element_type == "DATETIME": | 319 | | - return _datetime_from_json(value, None) | 320 | | - elif field.element_type == "TIMESTAMP": | 321 | | - return _timestamp_from_json(value, None) | | 318 | + if field.element_type in _SUPPORTED_RANGE_ELEMENTS: | | 319 | + return _CELLDATA_FROM_JSON[field.element_type](value, field.element_type) | 322 | 320 | else: | 323 | | - raise ValueError(f"Unsupported range field type: {value}") | | 321 | + raise ValueError(f"Unsupported range element type: {field.element_type}") | 324 | 322 |
| 325 | 323 |
| 326 | 324 | def _range_from_json(value, field): | @@ -344,7 +342,7 @@ def _range_from_json(value, field): | 344 | 342 | end = _range_element_from_json(end, field.range_element_type) | 345 | 343 | return {"start": start, "end": end} | 346 | 344 | else: | 347 | | - raise ValueError(f"Unknown range format: {value}") | | 345 | + raise ValueError(f"Unknown format for range value: {value}") | 348 | 346 | else: | 349 | 347 | return None | 350 | 348 |
| |
Collapse file Copy file name to clipboardExpand all lines: google/cloud/bigquery/_pandas_helpers.py +33Lines changed: 33 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -142,6 +142,17 @@ def bq_to_arrow_struct_data_type(field): | 142 | 142 | return pyarrow.struct(arrow_fields) | 143 | 143 |
| 144 | 144 |
| | 145 | +def bq_to_arrow_range_data_type(field): | | 146 | + if field is None: | | 147 | + raise ValueError( | | 148 | + "Range element type cannot be None, must be one of " | | 149 | + "DATE, DATETIME, or TIMESTAMP" | | 150 | + ) | | 151 | + element_type = field.element_type.upper() | | 152 | + arrow_element_type = _pyarrow_helpers.bq_to_arrow_scalars(element_type)() | | 153 | + return pyarrow.struct([("start", arrow_element_type), ("end", arrow_element_type)]) | | 154 | + | | 155 | + | 145 | 156 | def bq_to_arrow_data_type(field): | 146 | 157 | """Return the Arrow data type, corresponding to a given BigQuery column. | 147 | 158 |
| @@ -160,6 +171,9 @@ def bq_to_arrow_data_type(field): | 160 | 171 | if field_type_upper in schema._STRUCT_TYPES: | 161 | 172 | return bq_to_arrow_struct_data_type(field) | 162 | 173 |
| | 174 | + if field_type_upper == "RANGE": | | 175 | + return bq_to_arrow_range_data_type(field.range_element_type) | | 176 | + | 163 | 177 | data_type_constructor = _pyarrow_helpers.bq_to_arrow_scalars(field_type_upper) | 164 | 178 | if data_type_constructor is None: | 165 | 179 | return None | @@ -220,6 +234,9 @@ def default_types_mapper( | 220 | 234 | datetime_dtype: Union[Any, None] = None, | 221 | 235 | time_dtype: Union[Any, None] = None, | 222 | 236 | timestamp_dtype: Union[Any, None] = None, | | 237 | + range_date_dtype: Union[Any, None] = None, | | 238 | + range_datetime_dtype: Union[Any, None] = None, | | 239 | + range_timestamp_dtype: Union[Any, None] = None, | 223 | 240 | ): | 224 | 241 | """Create a mapping from pyarrow types to pandas types. | 225 | 242 |
| @@ -274,6 +291,22 @@ def types_mapper(arrow_data_type): | 274 | 291 | elif time_dtype is not None and pyarrow.types.is_time(arrow_data_type): | 275 | 292 | return time_dtype | 276 | 293 |
| | 294 | + elif pyarrow.types.is_struct(arrow_data_type): | | 295 | + if range_datetime_dtype is not None and arrow_data_type.equals( | | 296 | + range_datetime_dtype.pyarrow_dtype | | 297 | + ): | | 298 | + return range_datetime_dtype | | 299 | + | | 300 | + elif range_date_dtype is not None and arrow_data_type.equals( | | 301 | + range_date_dtype.pyarrow_dtype | | 302 | + ): | | 303 | + return range_date_dtype | | 304 | + | | 305 | + elif range_timestamp_dtype is not None and arrow_data_type.equals( | | 306 | + range_timestamp_dtype.pyarrow_dtype | | 307 | + ): | | 308 | + return range_timestamp_dtype | | 309 | + | 277 | 310 | return types_mapper | 278 | 311 |
| 279 | 312 |
| |
Collapse file Copy file name to clipboardExpand all lines: google/cloud/bigquery/dbapi/_helpers.py +8-6Lines changed: 8 additions & 6 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -277,12 +277,14 @@ def complex_query_parameter( | 277 | 277 | param = query.ArrayQueryParameter( | 278 | 278 | name, | 279 | 279 | sub_type, | 280 | | - value | 281 | | - if isinstance(sub_type, query.ScalarQueryParameterType) | 282 | | - else [ | 283 | | - complex_query_parameter(None, v, sub_type._complex__src, base) | 284 | | - for v in value | 285 | | - ], | | 280 | + ( | | 281 | + value | | 282 | + if isinstance(sub_type, query.ScalarQueryParameterType) | | 283 | + else [ | | 284 | + complex_query_parameter(None, v, sub_type._complex__src, base) | | 285 | + for v in value | | 286 | + ] | | 287 | + ), | 286 | 288 | ) | 287 | 289 | elif type_type == STRUCT: | 288 | 290 | if not isinstance(value, collections_abc.Mapping): | |
Collapse file Copy file name to clipboardExpand all lines: google/cloud/bigquery/enums.py +9Lines changed: 9 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -99,6 +99,15 @@ class DefaultPandasDTypes(enum.Enum): | 99 | 99 | TIME_DTYPE = object() | 100 | 100 | """Specifies default time dtype""" | 101 | 101 |
| | 102 | + RANGE_DATE_DTYPE = object() | | 103 | + """Specifies default range date dtype""" | | 104 | + | | 105 | + RANGE_DATETIME_DTYPE = object() | | 106 | + """Specifies default range datetime dtype""" | | 107 | + | | 108 | + RANGE_TIMESTAMP_DTYPE = object() | | 109 | + """Specifies default range timestamp dtype""" | | 110 | + | 102 | 111 |
| 103 | 112 | class DestinationFormat(object): | 104 | 113 | """The exported file format. The default value is :attr:`CSV`. | |
Collapse file Copy file name to clipboardExpand all lines: google/cloud/bigquery/job/query.py +67Lines changed: 67 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -1784,6 +1784,13 @@ def to_dataframe( | 1784 | 1784 | datetime_dtype: Union[Any, None] = None, | 1785 | 1785 | time_dtype: Union[Any, None] = DefaultPandasDTypes.TIME_DTYPE, | 1786 | 1786 | timestamp_dtype: Union[Any, None] = None, | | 1787 | + range_date_dtype: Union[Any, None] = DefaultPandasDTypes.RANGE_DATE_DTYPE, | | 1788 | + range_datetime_dtype: Union[ | | 1789 | + Any, None | | 1790 | + ] = DefaultPandasDTypes.RANGE_DATETIME_DTYPE, | | 1791 | + range_timestamp_dtype: Union[ | | 1792 | + Any, None | | 1793 | + ] = DefaultPandasDTypes.RANGE_TIMESTAMP_DTYPE, | 1787 | 1794 | ) -> "pandas.DataFrame": | 1788 | 1795 | """Return a pandas DataFrame from a QueryJob | 1789 | 1796 |
| @@ -1919,6 +1926,63 @@ def to_dataframe( | 1919 | 1926 |
| 1920 | 1927 | .. versionadded:: 3.10.0 | 1921 | 1928 |
| | 1929 | + range_date_dtype (Optional[pandas.Series.dtype, None]): | | 1930 | + If set, indicate a pandas ExtensionDtype, such as: | | 1931 | +
| | 1932 | + .. code-block:: python | | 1933 | +
| | 1934 | + pandas.ArrowDtype(pyarrow.struct( | | 1935 | + [("start", pyarrow.date32()), ("end", pyarrow.date32())] | | 1936 | + )) | | 1937 | +
| | 1938 | + to convert BigQuery RANGE<DATE> type, instead of relying on | | 1939 | + the default ``object``. If you explicitly set the value to | | 1940 | + ``None``, the data type will be ``object``. BigQuery Range type | | 1941 | + can be found at: | | 1942 | + https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#range_type | | 1943 | +
| | 1944 | + .. versionadded:: 3.21.0 | | 1945 | +
| | 1946 | + range_datetime_dtype (Optional[pandas.Series.dtype, None]): | | 1947 | + If set, indicate a pandas ExtensionDtype, such as: | | 1948 | +
| | 1949 | + .. code-block:: python | | 1950 | +
| | 1951 | + pandas.ArrowDtype(pyarrow.struct( | | 1952 | + [ | | 1953 | + ("start", pyarrow.timestamp("us")), | | 1954 | + ("end", pyarrow.timestamp("us")), | | 1955 | + ] | | 1956 | + )) | | 1957 | +
| | 1958 | + to convert BigQuery RANGE<DATETIME> type, instead of relying on | | 1959 | + the default ``object``. If you explicitly set the value to | | 1960 | + ``None``, the data type will be ``object``. BigQuery Range type | | 1961 | + can be found at: | | 1962 | + https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#range_type | | 1963 | +
| | 1964 | + .. versionadded:: 3.21.0 | | 1965 | +
| | 1966 | + range_timestamp_dtype (Optional[pandas.Series.dtype, None]): | | 1967 | + If set, indicate a pandas ExtensionDtype, such as: | | 1968 | +
| | 1969 | + .. code-block:: python | | 1970 | +
| | 1971 | + pandas.ArrowDtype(pyarrow.struct( | | 1972 | + [ | | 1973 | + ("start", pyarrow.timestamp("us", tz="UTC")), | | 1974 | + ("end", pyarrow.timestamp("us", tz="UTC")), | | 1975 | + ] | | 1976 | + )) | | 1977 | +
| | 1978 | + to convert BigQuery RANGE<TIMESTAMP> type, instead of relying | | 1979 | + on the default ``object``. If you explicitly set the value to | | 1980 | + ``None``, the data type will be ``object``. BigQuery Range type | | 1981 | + can be found at: | | 1982 | + https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#range_type | | 1983 | +
| | 1984 | + .. versionadded:: 3.21.0 | | 1985 | +
| 1922 | 1986 | Returns: | 1923 | 1987 | pandas.DataFrame: | 1924 | 1988 | A :class:`~pandas.DataFrame` populated with row data | @@ -1949,6 +2013,9 @@ def to_dataframe( | 1949 | 2013 | datetime_dtype=datetime_dtype, | 1950 | 2014 | time_dtype=time_dtype, | 1951 | 2015 | timestamp_dtype=timestamp_dtype, | | 2016 | + range_date_dtype=range_date_dtype, | | 2017 | + range_datetime_dtype=range_datetime_dtype, | | 2018 | + range_timestamp_dtype=range_timestamp_dtype, | 1952 | 2019 | ) | 1953 | 2020 |
| 1954 | 2021 | # If changing the signature of this method, make sure to apply the same | |
Collapse file Copy file name to clipboardExpand all lines: google/cloud/bigquery/query.py +5-6Lines changed: 5 additions & 6 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 24 | 24 | from google.cloud.bigquery._helpers import _rows_from_json | 25 | 25 | from google.cloud.bigquery._helpers import _QUERY_PARAMS_FROM_JSON | 26 | 26 | from google.cloud.bigquery._helpers import _SCALAR_VALUE_TO_JSON_PARAM | | 27 | +from google.cloud.bigquery._helpers import _SUPPORTED_RANGE_ELEMENTS | 27 | 28 |
| 28 | 29 |
| 29 | 30 | _SCALAR_VALUE_TYPE = Optional[ | 30 | 31 | Union[str, int, float, decimal.Decimal, bool, datetime.datetime, datetime.date] | 31 | 32 | ] | 32 | 33 |
| 33 | | -_RANGE_ELEMENT_TYPE_STR = {"TIMESTAMP", "DATETIME", "DATE"} | 34 | | - | 35 | 34 |
| 36 | 35 | class ConnectionProperty: | 37 | 36 | """A connection-level property to customize query behavior. | @@ -388,14 +387,14 @@ def _parse_range_element_type(self, type_): | 388 | 387 | google.cloud.bigquery.query.ScalarQueryParameterType: Instance | 389 | 388 | """ | 390 | 389 | if isinstance(type_, str): | 391 | | - if type_ not in _RANGE_ELEMENT_TYPE_STR: | | 390 | + if type_ not in _SUPPORTED_RANGE_ELEMENTS: | 392 | 391 | raise ValueError( | 393 | 392 | "If given as a string, range element type must be one of " | 394 | 393 | "'TIMESTAMP', 'DATE', or 'DATETIME'." | 395 | 394 | ) | 396 | 395 | return ScalarQueryParameterType(type_) | 397 | 396 | elif isinstance(type_, ScalarQueryParameterType): | 398 | | - if type_._type not in _RANGE_ELEMENT_TYPE_STR: | | 397 | + if type_._type not in _SUPPORTED_RANGE_ELEMENTS: | 399 | 398 | raise ValueError( | 400 | 399 | "If given as a ScalarQueryParameter object, range element " | 401 | 400 | "type must be one of 'TIMESTAMP', 'DATE', or 'DATETIME' " | @@ -960,14 +959,14 @@ class RangeQueryParameter(_AbstractQueryParameter): | 960 | 959 | @classmethod | 961 | 960 | def _parse_range_element_type(self, range_element_type): | 962 | 961 | if isinstance(range_element_type, str): | 963 | | - if range_element_type not in _RANGE_ELEMENT_TYPE_STR: | | 962 | + if range_element_type not in _SUPPORTED_RANGE_ELEMENTS: | 964 | 963 | raise ValueError( | 965 | 964 | "If given as a string, range_element_type must be one of " | 966 | 965 | f"'TIMESTAMP', 'DATE', or 'DATETIME'. Got {range_element_type}." | 967 | 966 | ) | 968 | 967 | return RangeQueryParameterType(range_element_type) | 969 | 968 | elif isinstance(range_element_type, RangeQueryParameterType): | 970 | | - if range_element_type.type_._type not in _RANGE_ELEMENT_TYPE_STR: | | 969 | + if range_element_type.type_._type not in _SUPPORTED_RANGE_ELEMENTS: | 971 | 970 | raise ValueError( | 972 | 971 | "If given as a RangeQueryParameterType object, " | 973 | 972 | "range_element_type must be one of 'TIMESTAMP', 'DATE', " | |
|