db-dtypes 1.4.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
db_dtypes/__init__.py ADDED
@@ -0,0 +1,366 @@
1
+ # Copyright 2021 Google LLC
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
+ # https://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
+ Pandas Data Types for SQL systems (BigQuery, Spanner)
16
+ """
17
+
18
+ import datetime
19
+ import re
20
+ from typing import Optional, Union
21
+ import warnings
22
+
23
+ import numpy
24
+ import pandas
25
+ import pandas.api.extensions
26
+ from pandas.errors import OutOfBoundsDatetime
27
+ import pyarrow
28
+ import pyarrow.compute
29
+
30
+ from db_dtypes import core
31
+ from db_dtypes.json import JSONArray, JSONDtype, JSONArrowType # noqa: F401
32
+
33
+ from . import _versions_helpers
34
+
35
+ date_dtype_name = "dbdate"
36
+ time_dtype_name = "dbtime"
37
+ _EPOCH = datetime.datetime(1970, 1, 1)
38
+ _NPEPOCH = numpy.datetime64(_EPOCH)
39
+ _NP_DTYPE = "datetime64[ns]"
40
+
41
+ # Numpy converts datetime64 scalars to datetime.datetime only if microsecond or
42
+ # smaller precision is used.
43
+ #
44
+ # TODO(https://github.com/googleapis/python-db-dtypes-pandas/issues/63): Keep
45
+ # nanosecond precision when boxing scalars.
46
+ _NP_BOX_DTYPE = "datetime64[us]"
47
+
48
+
49
+ @pandas.api.extensions.register_extension_dtype
50
+ class TimeDtype(core.BaseDatetimeDtype):
51
+ """
52
+ Extension dtype for time data.
53
+ """
54
+
55
+ name = time_dtype_name
56
+ type = datetime.time
57
+
58
+ def construct_array_type(self):
59
+ return TimeArray
60
+
61
+ @staticmethod
62
+ def __from_arrow__(
63
+ array: Union[pyarrow.Array, pyarrow.ChunkedArray]
64
+ ) -> "TimeArray":
65
+ """Convert to dbtime data from an Arrow array.
66
+
67
+ See:
68
+ https://pandas.pydata.org/pandas-docs/stable/development/extending.html#compatibility-with-apache-arrow
69
+ """
70
+ # We can't call combine_chunks on an empty array, so short-circuit the
71
+ # rest of the function logic for this special case.
72
+ if len(array) == 0:
73
+ return TimeArray(numpy.array([], dtype="datetime64[ns]"))
74
+
75
+ # We can't cast to timestamp("ns"), but time64("ns") has the same
76
+ # memory layout: 64-bit integers representing the number of nanoseconds
77
+ # since the datetime epoch (midnight 1970-01-01).
78
+ array = pyarrow.compute.cast(array, pyarrow.time64("ns"))
79
+
80
+ # ChunkedArray has no "view" method, so combine into an Array.
81
+ if isinstance(array, pyarrow.ChunkedArray):
82
+ array = array.combine_chunks()
83
+
84
+ array = array.view(pyarrow.timestamp("ns"))
85
+ np_array = array.to_numpy(zero_copy_only=False)
86
+ return TimeArray(np_array)
87
+
88
+
89
+ class TimeArray(core.BaseDatetimeArray):
90
+ """
91
+ Pandas array type containing time data
92
+ """
93
+
94
+ # Data are stored as datetime64 values with a date of Jan 1, 1970
95
+
96
+ dtype = TimeDtype()
97
+
98
+ @classmethod
99
+ def _datetime(
100
+ cls,
101
+ scalar,
102
+ match_fn=re.compile(
103
+ r"\s*(?P<hours>\d+)"
104
+ r"(?::(?P<minutes>\d+)"
105
+ r"(?::(?P<seconds>\d+)"
106
+ r"(?:\.(?P<fraction>\d*))?)?)?\s*$"
107
+ ).match,
108
+ ) -> Optional[numpy.datetime64]:
109
+ if isinstance(scalar, numpy.datetime64):
110
+ return scalar
111
+
112
+ # Convert pyarrow values to datetime.time.
113
+ if isinstance(scalar, (pyarrow.Time32Scalar, pyarrow.Time64Scalar)):
114
+ scalar = (
115
+ scalar.cast(pyarrow.time64("ns"))
116
+ .cast(pyarrow.int64())
117
+ .cast(pyarrow.timestamp("ns"))
118
+ .as_py()
119
+ )
120
+
121
+ if pandas.isna(scalar):
122
+ return numpy.datetime64("NaT")
123
+ if isinstance(scalar, datetime.time):
124
+ return pandas.Timestamp(
125
+ year=1970,
126
+ month=1,
127
+ day=1,
128
+ hour=scalar.hour,
129
+ minute=scalar.minute,
130
+ second=scalar.second,
131
+ microsecond=scalar.microsecond,
132
+ ).to_datetime64()
133
+ elif isinstance(scalar, pandas.Timestamp):
134
+ return scalar.to_datetime64()
135
+ elif isinstance(scalar, str):
136
+ # iso string
137
+ parsed = match_fn(scalar)
138
+ if not parsed:
139
+ raise ValueError(f"Bad time string: {repr(scalar)}")
140
+
141
+ hour = parsed.group("hours")
142
+ minute = parsed.group("minutes")
143
+ second = parsed.group("seconds")
144
+ fraction = parsed.group("fraction")
145
+ nanosecond = int(fraction.ljust(9, "0")[:9]) if fraction else 0
146
+
147
+ return pandas.Timestamp(
148
+ year=1970,
149
+ month=1,
150
+ day=1,
151
+ hour=int(hour),
152
+ minute=int(minute) if minute else 0,
153
+ second=int(second) if second else 0,
154
+ microsecond=nanosecond // 1000,
155
+ nanosecond=nanosecond % 1000,
156
+ ).to_datetime64()
157
+ else:
158
+ raise TypeError("Invalid value type", scalar)
159
+
160
+ def _box_func(self, x):
161
+ if pandas.isna(x):
162
+ return pandas.NaT
163
+
164
+ try:
165
+ return x.astype(_NP_BOX_DTYPE).item().time()
166
+ except AttributeError:
167
+ x = numpy.datetime64(
168
+ x, "ns"
169
+ ) # Integers are stored with nanosecond precision.
170
+ return x.astype(_NP_BOX_DTYPE).item().time()
171
+
172
+ __return_deltas = {"timedelta", "timedelta64", "timedelta64[ns]", "<m8", _NP_DTYPE}
173
+
174
+ def astype(self, dtype, copy=True):
175
+ deltas = self._ndarray - _NPEPOCH
176
+ stype = str(dtype)
177
+ if stype in self.__return_deltas:
178
+ return deltas
179
+ elif stype.startswith("timedelta64[") or stype.startswith("<m8["):
180
+ return deltas.astype(dtype, copy=False)
181
+ else:
182
+ return super().astype(dtype, copy=copy)
183
+
184
+ def __arrow_array__(self, type=None):
185
+ """Convert to an Arrow array from dbtime data.
186
+
187
+ See:
188
+ https://pandas.pydata.org/pandas-docs/stable/development/extending.html#compatibility-with-apache-arrow
189
+ """
190
+ array = pyarrow.array(self._ndarray, type=pyarrow.timestamp("ns"))
191
+
192
+ # ChunkedArray has no "view" method, so combine into an Array.
193
+ array = (
194
+ array.combine_chunks() if isinstance(array, pyarrow.ChunkedArray) else array
195
+ )
196
+
197
+ # We can't cast to time64("ns"), but timestamp("ns") has the same
198
+ # memory layout: 64-bit integers representing the number of nanoseconds
199
+ # since the datetime epoch (midnight 1970-01-01).
200
+ array = array.view(pyarrow.time64("ns"))
201
+ return pyarrow.compute.cast(
202
+ array,
203
+ type if type is not None else pyarrow.time64("ns"),
204
+ )
205
+
206
+
207
+ @pandas.api.extensions.register_extension_dtype
208
+ class DateDtype(core.BaseDatetimeDtype):
209
+ """
210
+ Extension dtype for time data.
211
+ """
212
+
213
+ name = date_dtype_name
214
+ type = datetime.date
215
+
216
+ def construct_array_type(self):
217
+ return DateArray
218
+
219
+ @staticmethod
220
+ def __from_arrow__(
221
+ array: Union[pyarrow.Array, pyarrow.ChunkedArray]
222
+ ) -> "DateArray":
223
+ """Convert to dbdate data from an Arrow array.
224
+
225
+ See:
226
+ https://pandas.pydata.org/pandas-docs/stable/development/extending.html#compatibility-with-apache-arrow
227
+ """
228
+ array = pyarrow.compute.cast(array, pyarrow.timestamp("ns"))
229
+ np_array = array.to_numpy()
230
+ return DateArray(np_array)
231
+
232
+
233
+ class DateArray(core.BaseDatetimeArray):
234
+ """
235
+ Pandas array type containing date data
236
+ """
237
+
238
+ # Data are stored as datetime64 values with a date of Jan 1, 1970
239
+
240
+ dtype = DateDtype()
241
+
242
+ @staticmethod
243
+ def _datetime(
244
+ scalar,
245
+ match_fn=re.compile(r"\s*(?P<year>\d+)-(?P<month>\d+)-(?P<day>\d+)\s*$").match,
246
+ ) -> Optional[numpy.datetime64]:
247
+ # Convert pyarrow values to datetime.date.
248
+ if isinstance(scalar, (pyarrow.Date32Scalar, pyarrow.Date64Scalar)):
249
+ scalar = scalar.as_py()
250
+
251
+ if pandas.isna(scalar):
252
+ return numpy.datetime64("NaT")
253
+ elif isinstance(scalar, numpy.datetime64):
254
+ dateObj = pandas.Timestamp(scalar)
255
+ elif isinstance(scalar, datetime.date):
256
+ dateObj = pandas.Timestamp(
257
+ year=scalar.year, month=scalar.month, day=scalar.day
258
+ )
259
+ elif isinstance(scalar, str):
260
+ match = match_fn(scalar)
261
+ if not match:
262
+ raise ValueError(f"Bad date string: {repr(scalar)}")
263
+ year = int(match.group("year"))
264
+ month = int(match.group("month"))
265
+ day = int(match.group("day"))
266
+
267
+ dateObj = pandas.Timestamp(
268
+ year=year,
269
+ month=month,
270
+ day=day,
271
+ )
272
+ else:
273
+ raise TypeError("Invalid value type", scalar)
274
+
275
+ # TODO(#64): Support larger ranges with other units.
276
+ if pandas.Timestamp.min < dateObj < pandas.Timestamp.max:
277
+ return dateObj.to_datetime64()
278
+ else: # pragma: NO COVER
279
+ # TODO(#166): Include these lines in coverage when pandas 2.0 is released.
280
+ raise OutOfBoundsDatetime("Out of bounds", scalar) # pragma: NO COVER
281
+
282
+ def _box_func(self, x):
283
+ if pandas.isna(x):
284
+ return pandas.NaT
285
+ try:
286
+ return x.astype(_NP_BOX_DTYPE).item().date()
287
+ except AttributeError:
288
+ x = numpy.datetime64(
289
+ x, "ns"
290
+ ) # Integers are stored with nanosecond precision.
291
+ return x.astype(_NP_BOX_DTYPE).item().date()
292
+
293
+ def astype(self, dtype, copy=True):
294
+ stype = str(dtype)
295
+ if stype.startswith("datetime"):
296
+ if stype == "datetime" or stype == "datetime64":
297
+ dtype = self._ndarray.dtype
298
+ return self._ndarray.astype(dtype, copy=copy)
299
+ elif stype.startswith("<M8"):
300
+ if stype == "<M8":
301
+ dtype = self._ndarray.dtype
302
+ return self._ndarray.astype(dtype, copy=copy)
303
+
304
+ return super().astype(dtype, copy=copy)
305
+
306
+ def __arrow_array__(self, type=None):
307
+ """Convert to an Arrow array from dbdate data.
308
+
309
+ See:
310
+ https://pandas.pydata.org/pandas-docs/stable/development/extending.html#compatibility-with-apache-arrow
311
+ """
312
+ array = pyarrow.array(self._ndarray, type=pyarrow.timestamp("ns"))
313
+ return pyarrow.compute.cast(
314
+ array,
315
+ type if type is not None else pyarrow.date32(),
316
+ )
317
+
318
+ def __add__(self, other):
319
+ if isinstance(other, pandas.DateOffset):
320
+ return self.astype("object") + other
321
+
322
+ if isinstance(other, TimeArray):
323
+ return (other._ndarray - _NPEPOCH) + self._ndarray
324
+
325
+ return super().__add__(other)
326
+
327
+ def __radd__(self, other):
328
+ return self.__add__(other)
329
+
330
+ def __sub__(self, other):
331
+ if isinstance(other, pandas.DateOffset):
332
+ return self.astype("object") - other
333
+
334
+ if isinstance(other, self.__class__):
335
+ return self._ndarray - other._ndarray
336
+
337
+ return super().__sub__(other)
338
+
339
+
340
+ def _check_python_version():
341
+ """Checks the runtime Python version and issues a warning if needed."""
342
+ sys_major, sys_minor, sys_micro = _versions_helpers.extract_runtime_version()
343
+ if sys_major == 3 and sys_minor in (7, 8):
344
+ warnings.warn(
345
+ "The python-bigquery library as well as the python-db-dtypes-pandas library no "
346
+ "longer supports Python 3.7 and Python 3.8. "
347
+ f"Your Python version is {sys_major}.{sys_minor}.{sys_micro}. We "
348
+ "recommend that you update soon to ensure ongoing support. For "
349
+ "more details, see: [Google Cloud Client Libraries Supported Python Versions policy](https://cloud.google.com/python/docs/supported-python-versions)",
350
+ FutureWarning,
351
+ stacklevel=2, # Point warning to the caller of __init__
352
+ )
353
+
354
+
355
+ _check_python_version()
356
+
357
+ __all__ = [
358
+ "__version__",
359
+ "DateArray",
360
+ "DateDtype",
361
+ "TimeArray",
362
+ "TimeDtype",
363
+ "JSONDtype",
364
+ "JSONArray",
365
+ "JSONArrowType",
366
+ ]
@@ -0,0 +1,32 @@
1
+ # Copyright 2024 Google LLC
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 verifying versions of installed modules."""
16
+
17
+
18
+ import sys
19
+ from typing import Tuple
20
+
21
+
22
+ def extract_runtime_version() -> Tuple[int, int, int]:
23
+ # Retrieve the version information
24
+ version_info = sys.version_info
25
+
26
+ # Extract the major, minor, and micro components
27
+ major = version_info.major
28
+ minor = version_info.minor
29
+ micro = version_info.micro
30
+
31
+ # Display the version number in a clear format
32
+ return major, minor, micro
db_dtypes/core.py ADDED
@@ -0,0 +1,195 @@
1
+ # Copyright 2021 Google LLC
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
+ from typing import Optional
16
+
17
+ import numpy
18
+ import pandas
19
+ import pandas.api.extensions
20
+ from pandas.api.types import is_dtype_equal, is_list_like, is_scalar, pandas_dtype
21
+ from pandas.core.arrays import _mixins
22
+
23
+ from db_dtypes import pandas_backports
24
+
25
+ pandas_release = pandas_backports.pandas_release
26
+
27
+
28
+ class BaseDatetimeDtype(pandas.api.extensions.ExtensionDtype):
29
+ na_value = pandas.NaT
30
+ kind = "O"
31
+ names = None
32
+
33
+ @classmethod
34
+ def construct_from_string(cls, name: str):
35
+ if not isinstance(name, str):
36
+ raise TypeError(
37
+ f"'construct_from_string' expects a string, got {type(name)}"
38
+ )
39
+
40
+ if name != cls.name:
41
+ raise TypeError(f"Cannot construct a '{cls.__name__}' from 'another_type'")
42
+
43
+ return cls()
44
+
45
+
46
+ class BaseDatetimeArray(pandas_backports.OpsMixin, _mixins.NDArrayBackedExtensionArray):
47
+ # scalar used to denote NA value inside our self._ndarray, e.g. -1 for
48
+ # Categorical, iNaT for Period. Outside of object dtype, self.isna() should
49
+ # be exactly locations in self._ndarray with _internal_fill_value. See:
50
+ # https://github.com/pandas-dev/pandas/blob/main/pandas/core/arrays/_mixins.py
51
+ _internal_fill_value = numpy.datetime64("NaT")
52
+
53
+ def __init__(self, values, dtype=None, copy: bool = False):
54
+ if not (
55
+ isinstance(values, numpy.ndarray) and values.dtype == numpy.dtype("<M8[ns]")
56
+ ):
57
+ values = self.__ndarray(values)
58
+ elif copy:
59
+ values = values.copy()
60
+
61
+ super().__init__(values=values, dtype=values.dtype)
62
+
63
+ @classmethod
64
+ def __ndarray(cls, scalars):
65
+ return numpy.array(
66
+ [cls._datetime(scalar) for scalar in scalars],
67
+ "M8[ns]",
68
+ )
69
+
70
+ @classmethod
71
+ def _from_sequence(cls, scalars, *, dtype=None, copy=False):
72
+ if dtype is not None:
73
+ assert dtype.__class__ is cls.dtype.__class__
74
+ return cls(cls.__ndarray(scalars))
75
+
76
+ _from_sequence_of_strings = _from_sequence
77
+
78
+ def astype(self, dtype, copy=True):
79
+ dtype = pandas_dtype(dtype)
80
+ if is_dtype_equal(dtype, self.dtype):
81
+ if not copy:
82
+ return self
83
+ else:
84
+ return self.copy()
85
+
86
+ return super().astype(dtype, copy=copy)
87
+
88
+ def _cmp_method(self, other, op):
89
+ """Compare array values, for use in OpsMixin."""
90
+
91
+ if is_scalar(other) and (
92
+ pandas.isna(other) or isinstance(other, self.dtype.type)
93
+ ):
94
+ other = type(self)([other])
95
+
96
+ if type(other) is not type(self):
97
+ return NotImplemented
98
+
99
+ oshape = getattr(other, "shape", None)
100
+ if oshape != self.shape and oshape != (1,) and self.shape != (1,):
101
+ raise TypeError(
102
+ "Can't compare arrays with different shapes", self.shape, oshape
103
+ )
104
+ return op(self._ndarray, other._ndarray)
105
+
106
+ def _from_factorized(self, unique, original):
107
+ return self.__class__(unique)
108
+
109
+ def isna(self):
110
+ return pandas.isna(self._ndarray)
111
+
112
+ def _validate_scalar(self, value):
113
+ """
114
+ Validate and convert a scalar value to datetime64[ns] for storage in
115
+ backing NumPy array.
116
+ """
117
+ return self._datetime(value)
118
+
119
+ def _validate_searchsorted_value(self, value):
120
+ """
121
+ Convert a value for use in searching for a value in the backing numpy array.
122
+
123
+ TODO: With pandas 2.0, this may be unnecessary. https://github.com/pandas-dev/pandas/pull/45544#issuecomment-1052809232
124
+ """
125
+ return self._validate_setitem_value(value)
126
+
127
+ def _validate_setitem_value(self, value):
128
+ """
129
+ Convert a value for use in setting a value in the backing numpy array.
130
+ """
131
+ if is_list_like(value):
132
+ _datetime = self._datetime
133
+ return [_datetime(v) for v in value]
134
+
135
+ return self._datetime(value)
136
+
137
+ def any(
138
+ self,
139
+ *,
140
+ axis: Optional[int] = None,
141
+ out=None,
142
+ keepdims: bool = False,
143
+ skipna: bool = True,
144
+ ):
145
+ pandas_backports.numpy_validate_any((), {"out": out, "keepdims": keepdims})
146
+ result = pandas_backports.nanany(self._ndarray, axis=axis, skipna=skipna)
147
+ return result
148
+
149
+ def all(
150
+ self,
151
+ *,
152
+ axis: Optional[int] = None,
153
+ out=None,
154
+ keepdims: bool = False,
155
+ skipna: bool = True,
156
+ ):
157
+ pandas_backports.numpy_validate_all((), {"out": out, "keepdims": keepdims})
158
+ result = pandas_backports.nanall(self._ndarray, axis=axis, skipna=skipna)
159
+ return result
160
+
161
+ def min(self, *, axis: Optional[int] = None, skipna: bool = True, **kwargs):
162
+ pandas_backports.numpy_validate_min((), kwargs)
163
+ result = pandas_backports.nanmin(
164
+ values=self._ndarray, axis=axis, mask=self.isna(), skipna=skipna
165
+ )
166
+ if axis is None or self.ndim == 1:
167
+ return self._box_func(result)
168
+ return self._from_backing_data(result)
169
+
170
+ def max(self, *, axis: Optional[int] = None, skipna: bool = True, **kwargs):
171
+ pandas_backports.numpy_validate_max((), kwargs)
172
+ result = pandas_backports.nanmax(
173
+ values=self._ndarray, axis=axis, mask=self.isna(), skipna=skipna
174
+ )
175
+ if axis is None or self.ndim == 1:
176
+ return self._box_func(result)
177
+ return self._from_backing_data(result)
178
+
179
+ def median(
180
+ self,
181
+ *,
182
+ axis: Optional[int] = None,
183
+ out=None,
184
+ overwrite_input: bool = False,
185
+ keepdims: bool = False,
186
+ skipna: bool = True,
187
+ ):
188
+ pandas_backports.numpy_validate_median(
189
+ (),
190
+ {"out": out, "overwrite_input": overwrite_input, "keepdims": keepdims},
191
+ )
192
+ result = pandas_backports.nanmedian(self._ndarray, axis=axis, skipna=skipna)
193
+ if axis is None or self.ndim == 1:
194
+ return self._box_func(result)
195
+ return self._from_backing_data(result)
db_dtypes/json.py ADDED
@@ -0,0 +1,281 @@
1
+ # Copyright 2024 Google LLC
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
+ # https://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
+ from __future__ import annotations
16
+
17
+ import json
18
+
19
+ import numpy as np
20
+ import pandas as pd
21
+ import pandas.arrays as arrays
22
+ import pandas.core.dtypes.common as common
23
+ import pandas.core.indexers as indexers
24
+ import pyarrow as pa
25
+ import pyarrow.compute
26
+
27
+
28
+ @pd.api.extensions.register_extension_dtype
29
+ class JSONDtype(pd.api.extensions.ExtensionDtype):
30
+ """Extension dtype for BigQuery JSON data."""
31
+
32
+ name = "dbjson"
33
+
34
+ @property
35
+ def na_value(self) -> pd.NA:
36
+ """Default NA value to use for this type."""
37
+ return pd.NA
38
+
39
+ @property
40
+ def type(self) -> type[str]:
41
+ """
42
+ Return the scalar type for the array elements.
43
+ The standard JSON data types can be one of `dict`, `list`, `str`, `int`, `float`,
44
+ `bool` and `None`. However, this method returns a `str` type to indicate its
45
+ storage type, because the union of multiple types are not supported well in pandas.
46
+ """
47
+ return str
48
+
49
+ @property
50
+ def pyarrow_dtype(self):
51
+ """Return the pyarrow data type used for storing data in the pyarrow array."""
52
+ return pa.string()
53
+
54
+ @property
55
+ def _is_numeric(self) -> bool:
56
+ return False
57
+
58
+ @property
59
+ def _is_boolean(self) -> bool:
60
+ return False
61
+
62
+ @classmethod
63
+ def construct_array_type(cls):
64
+ """Return the array type associated with this dtype."""
65
+ return JSONArray
66
+
67
+ def __from_arrow__(self, array: pa.Array | pa.ChunkedArray) -> JSONArray:
68
+ """Convert the pyarrow array to the extension array."""
69
+ return JSONArray(array)
70
+
71
+
72
+ class JSONArray(arrays.ArrowExtensionArray):
73
+ """Extension array that handles BigQuery JSON data, leveraging a string-based
74
+ pyarrow array for storage. It enables seamless conversion to JSON objects when
75
+ accessing individual elements."""
76
+
77
+ _dtype = JSONDtype()
78
+
79
+ def __init__(self, values) -> None:
80
+ super().__init__(values)
81
+ self._dtype = JSONDtype()
82
+ if isinstance(values, pa.Array):
83
+ pa_data = pa.chunked_array([values])
84
+ elif isinstance(values, pa.ChunkedArray):
85
+ pa_data = values
86
+ else:
87
+ raise NotImplementedError(
88
+ f"Unsupported type '{type(values)}' for JSONArray"
89
+ )
90
+
91
+ # Ensures compatibility with pandas version 1.5.3
92
+ if hasattr(self, "_data"):
93
+ self._data = pa_data
94
+ elif hasattr(self, "_pa_array"):
95
+ self._pa_array = pa_data
96
+ else:
97
+ raise NotImplementedError(f"Unsupported pandas version: {pd.__version__}")
98
+
99
+ def __arrow_array__(self, type=None):
100
+ """Convert to an arrow array. This is required for pyarrow extension."""
101
+ return pa.array(self.pa_data, type=JSONArrowType())
102
+
103
+ @classmethod
104
+ def _box_pa(
105
+ cls, value, pa_type: pa.DataType | None = None
106
+ ) -> pa.Array | pa.ChunkedArray | pa.Scalar:
107
+ """Box value into a pyarrow Array, ChunkedArray or Scalar."""
108
+ assert pa_type is None or pa_type == cls._dtype.pyarrow_dtype
109
+
110
+ if isinstance(value, pa.Scalar) or not (
111
+ common.is_list_like(value) and not common.is_dict_like(value)
112
+ ):
113
+ return cls._box_pa_scalar(value)
114
+ return cls._box_pa_array(value)
115
+
116
+ @classmethod
117
+ def _box_pa_scalar(cls, value) -> pa.Scalar:
118
+ """Box value into a pyarrow Scalar."""
119
+ if pd.isna(value):
120
+ pa_scalar = pa.scalar(None, type=cls._dtype.pyarrow_dtype)
121
+ else:
122
+ value = JSONArray._serialize_json(value)
123
+ pa_scalar = pa.scalar(
124
+ value, type=cls._dtype.pyarrow_dtype, from_pandas=True
125
+ )
126
+
127
+ return pa_scalar
128
+
129
+ @classmethod
130
+ def _box_pa_array(cls, value, copy: bool = False) -> pa.Array | pa.ChunkedArray:
131
+ """Box value into a pyarrow Array or ChunkedArray."""
132
+ if isinstance(value, cls):
133
+ pa_array = value.pa_data
134
+ else:
135
+ value = [JSONArray._serialize_json(x) for x in value]
136
+ pa_array = pa.array(value, type=cls._dtype.pyarrow_dtype, from_pandas=True)
137
+ return pa_array
138
+
139
+ @classmethod
140
+ def _from_sequence(cls, scalars, *, dtype=None, copy=False):
141
+ """Construct a new ExtensionArray from a sequence of scalars."""
142
+ pa_array = cls._box_pa(scalars)
143
+ arr = cls(pa_array)
144
+ return arr
145
+
146
+ @staticmethod
147
+ def _serialize_json(value):
148
+ """A static method that converts a JSON value into a string representation."""
149
+ if not common.is_list_like(value) and pd.isna(value):
150
+ return value
151
+ else:
152
+ # `sort_keys=True` sorts dictionary keys before serialization, making
153
+ # JSON comparisons deterministic.
154
+ # `separators=(',', ':')` eliminate whitespace to get the most compact
155
+ # JSON representation.
156
+ return json.dumps(value, sort_keys=True, separators=(",", ":"))
157
+
158
+ @staticmethod
159
+ def _deserialize_json(value):
160
+ """A static method that converts a JSON string back into its original value."""
161
+ if not pd.isna(value):
162
+ return json.loads(value)
163
+ else:
164
+ return value
165
+
166
+ @property
167
+ def dtype(self) -> JSONDtype:
168
+ """An instance of JSONDtype"""
169
+ return self._dtype
170
+
171
+ @property
172
+ def pa_data(self):
173
+ """An instance of stored pa data"""
174
+ # Ensures compatibility with pandas version 1.5.3
175
+ if hasattr(self, "_data"):
176
+ return self._data
177
+ elif hasattr(self, "_pa_array"):
178
+ return self._pa_array
179
+ else:
180
+ raise NotImplementedError(f"Unsupported pandas version: {pd.__version__}")
181
+
182
+ def _cmp_method(self, other, op):
183
+ if op.__name__ == "eq":
184
+ result = pyarrow.compute.equal(self.pa_data, self._box_pa(other))
185
+ elif op.__name__ == "ne":
186
+ result = pyarrow.compute.not_equal(self.pa_data, self._box_pa(other))
187
+ else:
188
+ # Comparison is not a meaningful one. We don't want to support sorting by JSON columns.
189
+ raise TypeError(f"{op.__name__} not supported for JSONArray")
190
+ return arrays.ArrowExtensionArray(result)
191
+
192
+ def __getitem__(self, item):
193
+ """Select a subset of self."""
194
+ item = indexers.check_array_indexer(self, item)
195
+
196
+ if isinstance(item, np.ndarray):
197
+ if not len(item):
198
+ return type(self)(pa.chunked_array([], type=self.dtype.pyarrow_dtype))
199
+ elif item.dtype.kind in "iu":
200
+ return self.take(item)
201
+ else:
202
+ # `check_array_indexer` should verify that the assertion hold true.
203
+ assert item.dtype.kind == "b"
204
+ return type(self)(self.pa_data.filter(item))
205
+ elif isinstance(item, tuple):
206
+ item = indexers.unpack_tuple_and_ellipses(item)
207
+
208
+ if common.is_scalar(item) and not common.is_integer(item):
209
+ # e.g. "foo" or 2.5
210
+ # exception message copied from numpy
211
+ raise IndexError(
212
+ r"only integers, slices (`:`), ellipsis (`...`), numpy.newaxis "
213
+ r"(`None`) and integer or boolean arrays are valid indices"
214
+ )
215
+
216
+ value = self.pa_data[item]
217
+ if isinstance(value, pa.ChunkedArray):
218
+ return type(self)(value)
219
+ elif isinstance(value, pa.ExtensionScalar):
220
+ return value.as_py()
221
+ else:
222
+ scalar = JSONArray._deserialize_json(value.as_py())
223
+ if scalar is None:
224
+ return self._dtype.na_value
225
+ else:
226
+ return scalar
227
+
228
+ def __iter__(self):
229
+ """Iterate over elements of the array."""
230
+ for value in self.pa_data:
231
+ val = JSONArray._deserialize_json(value.as_py())
232
+ if val is None:
233
+ yield self._dtype.na_value
234
+ else:
235
+ yield val
236
+
237
+ def _reduce(
238
+ self, name: str, *, skipna: bool = True, keepdims: bool = False, **kwargs
239
+ ):
240
+ """Return a scalar result of performing the reduction operation."""
241
+ if name in ["min", "max"]:
242
+ raise TypeError("JSONArray does not support min/max reducntion.")
243
+ super()._reduce(name, skipna=skipna, keepdims=keepdims, **kwargs)
244
+
245
+ def __array__(self, dtype=None, copy: bool | None = None) -> np.ndarray:
246
+ """Correctly construct numpy arrays when passed to `np.asarray()`."""
247
+ pa_type = self.pa_data.type
248
+ data = self
249
+ if dtype is None:
250
+ empty = pa.array([], type=pa_type).to_numpy(zero_copy_only=False)
251
+ dtype = empty.dtype
252
+ result = np.empty(len(data), dtype=dtype)
253
+ mask = data.isna()
254
+ result[mask] = self._dtype.na_value
255
+ result[~mask] = data[~mask].pa_data.to_numpy()
256
+ return result
257
+
258
+
259
+ class JSONArrowType(pa.ExtensionType):
260
+ """Arrow extension type for the `dbjson` Pandas extension type."""
261
+
262
+ def __init__(self) -> None:
263
+ super().__init__(pa.string(), "dbjson")
264
+
265
+ def __arrow_ext_serialize__(self) -> bytes:
266
+ return b""
267
+
268
+ @classmethod
269
+ def __arrow_ext_deserialize__(cls, storage_type, serialized) -> JSONArrowType:
270
+ return JSONArrowType()
271
+
272
+ def __hash__(self) -> int:
273
+ return hash(str(self))
274
+
275
+ def to_pandas_dtype(self):
276
+ return JSONDtype()
277
+
278
+
279
+ # Register the type to be included in RecordBatches, sent over IPC and received in
280
+ # another Python process.
281
+ pa.register_extension_type(JSONArrowType())
@@ -0,0 +1,74 @@
1
+ # Copyright 2021 Google LLC
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
+ """
16
+ Utilities to support older pandas versions.
17
+
18
+ These backported versions are simpler and, in some cases, less featureful than
19
+ the versions in the later versions of pandas.
20
+ """
21
+
22
+ import packaging.version
23
+ import pandas
24
+ import pandas.compat.numpy.function
25
+
26
+ pandas_release = packaging.version.parse(pandas.__version__).release
27
+
28
+ # # Create aliases for private methods in case they move in a future version.
29
+ nanall = pandas.core.nanops.nanall
30
+ nanany = pandas.core.nanops.nanany
31
+ nanmax = pandas.core.nanops.nanmax
32
+ nanmin = pandas.core.nanops.nanmin
33
+ numpy_validate_all = pandas.compat.numpy.function.validate_all
34
+ numpy_validate_any = pandas.compat.numpy.function.validate_any
35
+ numpy_validate_max = pandas.compat.numpy.function.validate_max
36
+ numpy_validate_min = pandas.compat.numpy.function.validate_min
37
+
38
+ nanmedian = pandas.core.nanops.nanmedian
39
+ numpy_validate_median = pandas.compat.numpy.function.validate_median
40
+
41
+
42
+ def import_default(module_name, force=False, default=None):
43
+ """
44
+ Provide an implementation for a class or function when it can't be imported
45
+
46
+ or when force is True.
47
+
48
+ This is used to replicate Pandas APIs that are missing or insufficient
49
+ (thus the force option) in early pandas versions.
50
+ """
51
+
52
+ if default is None:
53
+ return lambda func_or_class: import_default(module_name, force, func_or_class)
54
+
55
+ if force:
56
+ return default
57
+
58
+ name = default.__name__
59
+ try:
60
+ module = __import__(module_name, {}, {}, [name])
61
+ except ModuleNotFoundError:
62
+ return default
63
+
64
+ return getattr(module, name, default)
65
+
66
+
67
+ # pandas.core.arraylike.OpsMixin is private, but the related public API
68
+ # "ExtensionScalarOpsMixin" is not sufficient for adding dates to times.
69
+ # It results in unsupported operand type(s) for +: 'datetime.time' and
70
+ # 'datetime.date'
71
+ @import_default("pandas.core.arraylike")
72
+ class OpsMixin:
73
+ def _cmp_method(self, other, op): # pragma: NO COVER
74
+ return NotImplemented
db_dtypes/version.py ADDED
@@ -0,0 +1,15 @@
1
+ # Copyright 2021 Google LLC
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
+ # https://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
+ __version__ = "1.4.3" # pragma: NO COVER
@@ -0,0 +1,9 @@
1
+ # This is the list of db-dtypes's significant contributors.
2
+ #
3
+ # This does not necessarily list everyone who has contributed code,
4
+ # especially since many employees of one corporation may be contributing.
5
+ # To see the full list of contributors, see the revision history in
6
+ # source control.
7
+ Google LLC
8
+ Jim Fulton
9
+ Tim Swast (tswast)
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.1
2
+ Name: db-dtypes
3
+ Version: 1.4.3
4
+ Summary: Pandas Data Types for SQL systems (BigQuery, Spanner)
5
+ Home-page: https://github.com/googleapis/python-db-dtypes-pandas
6
+ Author: The db-dtypes Authors
7
+ Author-email: googleapis-packages@google.com
8
+ Keywords: sql,pandas
9
+ Platform: Posix; MacOS X; Windows
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Operating System :: OS Independent
21
+ Classifier: Topic :: Database :: Front-Ends
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/x-rst
24
+ License-File: LICENSE
25
+ License-File: AUTHORS
26
+ Requires-Dist: numpy>=1.24.0
27
+ Requires-Dist: packaging>=24.2.0
28
+ Requires-Dist: pandas>=1.5.3
29
+ Requires-Dist: pyarrow>=13.0.0
30
+
31
+ Pandas Data Types for SQL systems (BigQuery, Spanner)
32
+ =====================================================
33
+
34
+ |ga| |pypi| |versions|
35
+
36
+ `Pandas extension data types`_ for data from SQL systems such as `BigQuery`_.
37
+
38
+ - `Library Documentation`_
39
+
40
+ .. |ga| image:: https://img.shields.io/badge/support-GA-gold.svg
41
+ :target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#general-availability
42
+ .. |pypi| image:: https://img.shields.io/pypi/v/db-dtypes.svg
43
+ :target: https://pypi.org/project/db-dtypes/
44
+ .. |versions| image:: https://img.shields.io/pypi/pyversions/db-dtypes.svg
45
+ :target: https://pypi.org/project/db-dtypes/
46
+ .. _Pandas extension data types: https://pandas.pydata.org/docs/development/extending.html#extension-types
47
+ .. _BigQuery: https://cloud.google.com/bigquery/docs/
48
+ .. _Library Documentation: https://googleapis.dev/python/db-dtypes/latest
49
+
50
+
51
+ Installation
52
+ ------------
53
+
54
+ Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to
55
+ create isolated Python environments. The basic problem it addresses is one of
56
+ dependencies and versions, and indirectly permissions.
57
+
58
+ With `virtualenv`_, it's possible to install this library without needing system
59
+ install permissions, and without clashing with the installed system
60
+ dependencies.
61
+
62
+ .. _`virtualenv`: https://virtualenv.pypa.io/en/latest/
63
+
64
+
65
+ Supported Python Versions
66
+ ^^^^^^^^^^^^^^^^^^^^^^^^^
67
+ Python >= 3.9
68
+
69
+ Unsupported Python Versions
70
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
71
+ Python <= 3.8.
72
+
73
+
74
+ Mac/Linux
75
+ ^^^^^^^^^
76
+
77
+ .. code-block:: console
78
+
79
+ pip install virtualenv
80
+ virtualenv <your-env>
81
+ source <your-env>/bin/activate
82
+ <your-env>/bin/pip install db-dtypes
83
+
84
+
85
+ Windows
86
+ ^^^^^^^
87
+
88
+ .. code-block:: console
89
+
90
+ pip install virtualenv
91
+ virtualenv <your-env>
92
+ <your-env>\Scripts\activate
93
+ <your-env>\Scripts\pip.exe install db-dtypes
@@ -0,0 +1,12 @@
1
+ db_dtypes/__init__.py,sha256=Lq8VKd1X7hdaHIwYoLOWe4Hj3UT5PNgZaSIgx9nnUh4,12259
2
+ db_dtypes/_versions_helpers.py,sha256=ChEUHNB1zLfn1RwAiuh3TyyATuq7rdSNAYW-DkKFphs,1050
3
+ db_dtypes/core.py,sha256=p3rmWRqJ6ryWyMyyUVeH3btLO2xp5HjxjoGwD-zkkqU,6572
4
+ db_dtypes/json.py,sha256=UMno-4dCC3ldOUNXTSRPFG7LHBV08h1Zk5BwZJBdVz8,10029
5
+ db_dtypes/pandas_backports.py,sha256=ZIQsNY-Nz1gbAgMSu2034XTLk-ZEGKgmU4S71JShGps,2521
6
+ db_dtypes/version.py,sha256=RGho-Ro8RZTtDee-enRlIndtWLt_3udMRn1zWdA3-9o,618
7
+ db_dtypes-1.4.3.dist-info/AUTHORS,sha256=ZzwnqDCA5-5_W_beU6-64JXYg_8IyNUp7aHfvZHowmI,331
8
+ db_dtypes-1.4.3.dist-info/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
9
+ db_dtypes-1.4.3.dist-info/METADATA,sha256=waf9H7MnIJDqMFXu6U6sp0k52U5WFQ8SIeve3G4ZjH4,2970
10
+ db_dtypes-1.4.3.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
11
+ db_dtypes-1.4.3.dist-info/top_level.txt,sha256=Lzrj78HENTzHjW4Xb-xOlAuHlAgu4z8nG9NrXPqZKJk,10
12
+ db_dtypes-1.4.3.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.3.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ db_dtypes