quasardb 3.14.2.dev7__cp310-cp310-manylinux_2_26_aarch64.manylinux_2_28_aarch64.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.
Potentially problematic release.
This version of quasardb might be problematic. Click here for more details.
- quasardb/CMakeFiles/CMakeDirectoryInformation.cmake +16 -0
- quasardb/CMakeFiles/progress.marks +1 -0
- quasardb/Makefile +189 -0
- quasardb/__init__.py +140 -0
- quasardb/__init__.pyi +72 -0
- quasardb/cmake_install.cmake +58 -0
- quasardb/date/CMakeFiles/CMakeDirectoryInformation.cmake +16 -0
- quasardb/date/CMakeFiles/Export/b76006b2b7125baf1b0b4d4ca4db82bd/dateTargets.cmake +108 -0
- quasardb/date/CMakeFiles/progress.marks +1 -0
- quasardb/date/Makefile +189 -0
- quasardb/date/cmake_install.cmake +81 -0
- quasardb/date/dateConfigVersion.cmake +65 -0
- quasardb/date/dateTargets.cmake +63 -0
- quasardb/extensions/__init__.py +8 -0
- quasardb/extensions/writer.py +191 -0
- quasardb/firehose.py +103 -0
- quasardb/libqdb_api.so +0 -0
- quasardb/numpy/__init__.py +1045 -0
- quasardb/pandas/__init__.py +533 -0
- quasardb/pool.py +311 -0
- quasardb/pybind11/CMakeFiles/CMakeDirectoryInformation.cmake +16 -0
- quasardb/pybind11/CMakeFiles/progress.marks +1 -0
- quasardb/pybind11/Makefile +189 -0
- quasardb/pybind11/cmake_install.cmake +50 -0
- quasardb/quasardb/__init__.pyi +97 -0
- quasardb/quasardb/_batch_column.pyi +5 -0
- quasardb/quasardb/_batch_inserter.pyi +30 -0
- quasardb/quasardb/_blob.pyi +16 -0
- quasardb/quasardb/_cluster.pyi +100 -0
- quasardb/quasardb/_continuous.pyi +16 -0
- quasardb/quasardb/_double.pyi +7 -0
- quasardb/quasardb/_entry.pyi +60 -0
- quasardb/quasardb/_error.pyi +15 -0
- quasardb/quasardb/_integer.pyi +7 -0
- quasardb/quasardb/_node.pyi +26 -0
- quasardb/quasardb/_options.pyi +105 -0
- quasardb/quasardb/_perf.pyi +5 -0
- quasardb/quasardb/_properties.pyi +5 -0
- quasardb/quasardb/_query.pyi +2 -0
- quasardb/quasardb/_reader.pyi +9 -0
- quasardb/quasardb/_retry.pyi +16 -0
- quasardb/quasardb/_string.pyi +12 -0
- quasardb/quasardb/_table.pyi +125 -0
- quasardb/quasardb/_tag.pyi +5 -0
- quasardb/quasardb/_timestamp.pyi +9 -0
- quasardb/quasardb/_writer.pyi +111 -0
- quasardb/quasardb/metrics/__init__.pyi +20 -0
- quasardb/quasardb.cpython-310-aarch64-linux-gnu.so +0 -0
- quasardb/range-v3/CMakeFiles/CMakeDirectoryInformation.cmake +16 -0
- quasardb/range-v3/CMakeFiles/Export/48a02d54b5e9e60c30c5f249b431a911/range-v3-targets.cmake +128 -0
- quasardb/range-v3/CMakeFiles/progress.marks +1 -0
- quasardb/range-v3/CMakeFiles/range.v3.headers.dir/DependInfo.cmake +22 -0
- quasardb/range-v3/CMakeFiles/range.v3.headers.dir/build.make +86 -0
- quasardb/range-v3/CMakeFiles/range.v3.headers.dir/cmake_clean.cmake +5 -0
- quasardb/range-v3/CMakeFiles/range.v3.headers.dir/compiler_depend.make +2 -0
- quasardb/range-v3/CMakeFiles/range.v3.headers.dir/compiler_depend.ts +2 -0
- quasardb/range-v3/CMakeFiles/range.v3.headers.dir/progress.make +1 -0
- quasardb/range-v3/Makefile +204 -0
- quasardb/range-v3/cmake_install.cmake +93 -0
- quasardb/range-v3/include/range/v3/version.hpp +24 -0
- quasardb/range-v3/range-v3-config-version.cmake +83 -0
- quasardb/range-v3/range-v3-config.cmake +80 -0
- quasardb/stats.py +358 -0
- quasardb/table_cache.py +56 -0
- quasardb-3.14.2.dev7.dist-info/METADATA +41 -0
- quasardb-3.14.2.dev7.dist-info/RECORD +69 -0
- quasardb-3.14.2.dev7.dist-info/WHEEL +6 -0
- quasardb-3.14.2.dev7.dist-info/licenses/LICENSE.md +11 -0
- quasardb-3.14.2.dev7.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1045 @@
|
|
|
1
|
+
# pylint: disable=C0103,C0111,C0302,R0903
|
|
2
|
+
|
|
3
|
+
# Copyright (c) 2009-2022, quasardb SAS. All rights reserved.
|
|
4
|
+
# All rights reserved.
|
|
5
|
+
#
|
|
6
|
+
# Redistribution and use in source and binary forms, with or without
|
|
7
|
+
# modification, are permitted provided that the following conditions are met:
|
|
8
|
+
#
|
|
9
|
+
# * Redistributions of source code must retain the above copyright
|
|
10
|
+
# notice, this list of conditions and the following disclaimer.
|
|
11
|
+
# * Redistributions in binary form must reproduce the above copyright
|
|
12
|
+
# notice, this list of conditions and the following disclaimer in the
|
|
13
|
+
# documentation and/or other materials provided with the distribution.
|
|
14
|
+
# * Neither the name of quasardb nor the names of its contributors may
|
|
15
|
+
# be used to endorse or promote products derived from this software
|
|
16
|
+
# without specific prior written permission.
|
|
17
|
+
#
|
|
18
|
+
# THIS SOFTWARE IS PROVIDED BY QUASARDB AND CONTRIBUTORS ``AS IS'' AND ANY
|
|
19
|
+
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
20
|
+
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
21
|
+
# DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
|
|
22
|
+
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
|
23
|
+
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
|
24
|
+
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
|
25
|
+
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
26
|
+
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
|
27
|
+
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
28
|
+
#
|
|
29
|
+
|
|
30
|
+
import logging
|
|
31
|
+
import time
|
|
32
|
+
import warnings
|
|
33
|
+
from typing import Dict, List, Optional, Tuple, Union
|
|
34
|
+
from numpy.typing import DTypeLike
|
|
35
|
+
|
|
36
|
+
import quasardb
|
|
37
|
+
import quasardb.table_cache as table_cache
|
|
38
|
+
|
|
39
|
+
logger = logging.getLogger("quasardb.numpy")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class NumpyRequired(ImportError):
|
|
43
|
+
"""
|
|
44
|
+
Exception raised when trying to use QuasarDB pandas integration, but
|
|
45
|
+
pandas has not been installed.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
pass
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
try:
|
|
52
|
+
import numpy as np
|
|
53
|
+
import numpy.ma as ma
|
|
54
|
+
|
|
55
|
+
except ImportError as err:
|
|
56
|
+
logger.exception(err)
|
|
57
|
+
raise NumpyRequired(
|
|
58
|
+
"The numpy library is required to handle numpy arrays formats"
|
|
59
|
+
) from err
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class IncompatibleDtypeError(TypeError):
|
|
63
|
+
"""
|
|
64
|
+
Exception raised when a provided dtype is not the expected dtype.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
def __init__(self, cname=None, ctype=None, expected=None, provided=None) -> None:
|
|
68
|
+
self.cname = cname
|
|
69
|
+
self.ctype = ctype
|
|
70
|
+
self.expected = expected
|
|
71
|
+
self.provided = provided
|
|
72
|
+
super().__init__(self.msg())
|
|
73
|
+
|
|
74
|
+
def msg(self) -> str:
|
|
75
|
+
return "Data for column '{}' with type '{}' was provided in dtype '{}' but need '{}'.".format(
|
|
76
|
+
self.cname, self.ctype, self.provided, self.expected
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class IncompatibleDtypeErrors(TypeError):
|
|
81
|
+
"""
|
|
82
|
+
Wraps multiple dtype errors
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
def __init__(self, xs) -> None:
|
|
86
|
+
self.xs = xs
|
|
87
|
+
super().__init__(self.msg())
|
|
88
|
+
|
|
89
|
+
def msg(self) -> str:
|
|
90
|
+
return "\n".join(x.msg() for x in self.xs)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class InvalidDataCardinalityError(ValueError):
|
|
94
|
+
"""
|
|
95
|
+
Raised when the provided data arrays doesn't match the table's columns.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
def __init__(self, data, cinfos) -> None:
|
|
99
|
+
self.data = data
|
|
100
|
+
self.cinfos = cinfos
|
|
101
|
+
super().__init__(self.msg())
|
|
102
|
+
|
|
103
|
+
def msg(self) -> str:
|
|
104
|
+
return "Provided data array length '{}' exceeds amount of table columns '{}', unable to map data to columns".format(
|
|
105
|
+
len(self.data), len(self.cinfos)
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# Based on QuasarDB column types, which dtype do we accept?
|
|
110
|
+
# First entry will always be the 'preferred' dtype, other ones
|
|
111
|
+
# those that we can natively convert in native code.
|
|
112
|
+
_ctype_to_dtype = {
|
|
113
|
+
quasardb.ColumnType.String: [np.dtype("U")],
|
|
114
|
+
quasardb.ColumnType.Symbol: [np.dtype("U")],
|
|
115
|
+
quasardb.ColumnType.Int64: [np.dtype("i8"), np.dtype("i4"), np.dtype("i2")],
|
|
116
|
+
quasardb.ColumnType.Double: [np.dtype("f8"), np.dtype("f4")],
|
|
117
|
+
quasardb.ColumnType.Blob: [np.dtype("S"), np.dtype("O")],
|
|
118
|
+
quasardb.ColumnType.Timestamp: [np.dtype("datetime64[ns]")],
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _best_dtype_for_ctype(ctype: quasardb.ColumnType):
|
|
123
|
+
"""
|
|
124
|
+
Returns the 'best' DType for a certain column type. For example, for blobs, even
|
|
125
|
+
though we accept py::bytes, prefer bytestrings (as they are faster to read in c++).
|
|
126
|
+
"""
|
|
127
|
+
possible_dtypes = _ctype_to_dtype[ctype]
|
|
128
|
+
assert len(possible_dtypes) > 0
|
|
129
|
+
|
|
130
|
+
# By convention, the first entry is the preferred one
|
|
131
|
+
return possible_dtypes[0]
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _coerce_dtype(
|
|
135
|
+
dtype: Union[DTypeLike, Dict[str, DTypeLike], List[DTypeLike]],
|
|
136
|
+
columns: List[Tuple[str, quasardb.ColumnInfo]],
|
|
137
|
+
) -> List[DTypeLike]:
|
|
138
|
+
if dtype is None:
|
|
139
|
+
dtype = [None] * len(columns)
|
|
140
|
+
|
|
141
|
+
if isinstance(dtype, np.dtype):
|
|
142
|
+
dtype = [dtype]
|
|
143
|
+
|
|
144
|
+
if type(dtype) is dict:
|
|
145
|
+
# Conveniently look up column index by label
|
|
146
|
+
offsets = {}
|
|
147
|
+
for i in range(len(columns)):
|
|
148
|
+
(cname, _) = columns[i]
|
|
149
|
+
offsets[cname] = i
|
|
150
|
+
|
|
151
|
+
# Now convert the provided dtype dict to a list that matches
|
|
152
|
+
# the relative offset within the table.
|
|
153
|
+
#
|
|
154
|
+
# Any columns not provided will have a 'None' dtype.
|
|
155
|
+
dtype_ = [None] * len(columns)
|
|
156
|
+
|
|
157
|
+
for k, dt in dtype.items():
|
|
158
|
+
if not k in offsets:
|
|
159
|
+
logger.warning(
|
|
160
|
+
"Forced dtype provided for column '%s' = %s, but that column is not found in the table. Skipping...",
|
|
161
|
+
k,
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
i = offsets[k]
|
|
165
|
+
dtype_[i] = dt
|
|
166
|
+
|
|
167
|
+
dtype = dtype_
|
|
168
|
+
|
|
169
|
+
if type(dtype) is not list:
|
|
170
|
+
raise ValueError(
|
|
171
|
+
"Forced dtype argument provided, but the argument has an incompatible type. Expected: list-like or dict-like, got: {}".format(
|
|
172
|
+
type(dtype)
|
|
173
|
+
)
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
if len(dtype) is not len(columns):
|
|
177
|
+
raise ValueError(
|
|
178
|
+
"Expected exactly one dtype for each column, but %d dtypes were provided for %d columns".format(
|
|
179
|
+
len(dtype), len(columns)
|
|
180
|
+
)
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
return dtype
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _add_desired_dtypes(
|
|
187
|
+
dtype: List[DTypeLike], columns: List[Tuple[str, quasardb.ColumnInfo]]
|
|
188
|
+
) -> List[DTypeLike]:
|
|
189
|
+
"""
|
|
190
|
+
When infer_types=True, this function sets the 'desired' dtype for each of the columns.
|
|
191
|
+
`dtype` is expected to be the output of `_coerce_dtype`, that is, a list-like with an
|
|
192
|
+
entry for each column.
|
|
193
|
+
"""
|
|
194
|
+
assert len(dtype) == len(columns)
|
|
195
|
+
|
|
196
|
+
for i in range(len(dtype)):
|
|
197
|
+
# No dtype explicitly provided by the user, otherwise we don't touch it
|
|
198
|
+
if dtype[i] is None:
|
|
199
|
+
(cname, ctype) = columns[i]
|
|
200
|
+
dtype_ = _best_dtype_for_ctype(ctype)
|
|
201
|
+
logger.debug(
|
|
202
|
+
"using default dtype '%s' for column '%s' with type %s",
|
|
203
|
+
dtype_,
|
|
204
|
+
cname,
|
|
205
|
+
ctype,
|
|
206
|
+
)
|
|
207
|
+
dtype[i] = dtype_
|
|
208
|
+
|
|
209
|
+
return dtype
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _is_all_masked(xs):
|
|
213
|
+
if ma.isMA(xs):
|
|
214
|
+
return ma.size(xs) == ma.count_masked(xs)
|
|
215
|
+
|
|
216
|
+
if np.size(xs) == 0:
|
|
217
|
+
# Empty lists are considered "masked"
|
|
218
|
+
return True
|
|
219
|
+
|
|
220
|
+
if xs.dtype == np.object_ and xs[0] is None:
|
|
221
|
+
# Very likely that all is None at this point, we can try a more "expensive"
|
|
222
|
+
# probing function
|
|
223
|
+
#
|
|
224
|
+
# We'll defer to the Python `all` function, as Numpy doesn't really have great
|
|
225
|
+
# built-ins for object arrays
|
|
226
|
+
return all(x is None for x in xs)
|
|
227
|
+
|
|
228
|
+
logger.debug(
|
|
229
|
+
"{} is not a masked array, not convertible to requested type... ".format(
|
|
230
|
+
type(xs)
|
|
231
|
+
)
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
# This array is *not* a masked array, it's *not* convertible to the type we want,
|
|
235
|
+
# and it's *not* an object array.
|
|
236
|
+
#
|
|
237
|
+
# The best we can do at this point is emit a warning and defer to the (expensive)
|
|
238
|
+
# python-based function as well.
|
|
239
|
+
return all(x is None for x in xs)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def dtypes_equal(lhs, rhs):
|
|
243
|
+
if lhs.kind == "U" or lhs.kind == "S":
|
|
244
|
+
# Unicode and string data has variable length encoding, which means their itemsize
|
|
245
|
+
# can be anything.
|
|
246
|
+
#
|
|
247
|
+
# We only care about dtype kind in this case.
|
|
248
|
+
return lhs.kind == rhs.kind
|
|
249
|
+
|
|
250
|
+
return lhs == rhs
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _dtype_found(needle, haystack):
|
|
254
|
+
"""
|
|
255
|
+
Returns True if one of the dtypes in `haystack` matches that of `needle`.
|
|
256
|
+
"""
|
|
257
|
+
for x in haystack:
|
|
258
|
+
if dtypes_equal(needle, x) is True:
|
|
259
|
+
return True
|
|
260
|
+
|
|
261
|
+
return False
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _validate_dtypes(data, columns):
|
|
265
|
+
errors = list()
|
|
266
|
+
|
|
267
|
+
def _error_to_msg(e):
|
|
268
|
+
(cname, ctype, provided_dtype, expected_dtype) = e
|
|
269
|
+
return
|
|
270
|
+
|
|
271
|
+
for data_, (cname, ctype) in zip(data, columns):
|
|
272
|
+
expected_ = _ctype_to_dtype[ctype]
|
|
273
|
+
|
|
274
|
+
logger.debug("data_.dtype = %s, expected_ = %s", data_.dtype, expected_)
|
|
275
|
+
|
|
276
|
+
if _dtype_found(data_.dtype, expected_) == False:
|
|
277
|
+
errors.append(
|
|
278
|
+
IncompatibleDtypeError(
|
|
279
|
+
cname=cname, ctype=ctype, provided=data_.dtype, expected=expected_
|
|
280
|
+
)
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
if len(errors) > 0:
|
|
284
|
+
raise IncompatibleDtypeErrors(errors)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _coerce_deduplicate(deduplicate, deduplication_mode, columns):
|
|
288
|
+
"""
|
|
289
|
+
Throws an error when 'deduplicate' options are incorrect.
|
|
290
|
+
"""
|
|
291
|
+
cnames = [cname for (cname, ctype) in columns]
|
|
292
|
+
|
|
293
|
+
if deduplication_mode not in ["drop", "upsert"]:
|
|
294
|
+
raise RuntimeError(
|
|
295
|
+
"deduplication_mode should be one of ['drop', 'upsert'], got: {}".format(
|
|
296
|
+
deduplication_mode
|
|
297
|
+
)
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
if isinstance(deduplicate, bool):
|
|
301
|
+
return deduplicate
|
|
302
|
+
|
|
303
|
+
# Special value of $timestamp, hardcoded
|
|
304
|
+
if isinstance(deduplicate, str) and deduplicate == "$timestamp":
|
|
305
|
+
deduplicate = ["$timestamp"]
|
|
306
|
+
cnames.append("$timestamp")
|
|
307
|
+
|
|
308
|
+
if not isinstance(deduplicate, list):
|
|
309
|
+
raise TypeError(
|
|
310
|
+
"drop_duplicates should be either a bool or a list, got: "
|
|
311
|
+
+ type(deduplicate)
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
for column_name in deduplicate:
|
|
315
|
+
if not column_name in cnames:
|
|
316
|
+
raise RuntimeError(
|
|
317
|
+
"Provided deduplication column name '{}' not found in table columns.".format(
|
|
318
|
+
column_name
|
|
319
|
+
)
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
return deduplicate
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _clean_nulls(xs, dtype):
|
|
326
|
+
"""
|
|
327
|
+
Numpy's masked arrays have a downside that in case they're not able to convert a (masked!) value to
|
|
328
|
+
the desired dtype, they raise an error. So, for example, if I have a masked array of objects that
|
|
329
|
+
look like this
|
|
330
|
+
|
|
331
|
+
xs: [1.234 <pd.NA> 5.678]
|
|
332
|
+
mask: [1 0 1]
|
|
333
|
+
|
|
334
|
+
even though pd.NA is not "visible", because it cannot be converted to a float(), the operation will
|
|
335
|
+
fail!
|
|
336
|
+
|
|
337
|
+
This function fixes this by replacing the null values with an acceptable value that can always be
|
|
338
|
+
converted to the desired dtype.
|
|
339
|
+
"""
|
|
340
|
+
|
|
341
|
+
assert ma.isMA(xs)
|
|
342
|
+
|
|
343
|
+
if xs.dtype is not np.dtype("object"):
|
|
344
|
+
return xs
|
|
345
|
+
|
|
346
|
+
fill_value = None
|
|
347
|
+
if dtype == np.float64 or dtype == np.float32 or dtype == np.float16:
|
|
348
|
+
fill_value = float("nan")
|
|
349
|
+
elif dtype == np.int64 or dtype == np.int32 or dtype == np.int16:
|
|
350
|
+
fill_value = -1
|
|
351
|
+
elif dtype == np.dtype("datetime64[ns]"):
|
|
352
|
+
fill_value = np.datetime64("nat")
|
|
353
|
+
|
|
354
|
+
mask = xs.mask
|
|
355
|
+
xs_ = xs.filled(fill_value)
|
|
356
|
+
|
|
357
|
+
return ma.array(xs_, mask=mask)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _coerce_data(data, dtype):
|
|
361
|
+
"""
|
|
362
|
+
Coerces each numpy array of `data` to the dtype present in `dtype`.
|
|
363
|
+
"""
|
|
364
|
+
|
|
365
|
+
assert len(data) == len(dtype)
|
|
366
|
+
|
|
367
|
+
for i in range(len(data)):
|
|
368
|
+
dtype_ = dtype[i]
|
|
369
|
+
data_ = data[i]
|
|
370
|
+
|
|
371
|
+
if dtype_ is not None and dtypes_equal(data_.dtype, dtype_) == False:
|
|
372
|
+
data_ = _clean_nulls(data_, dtype_)
|
|
373
|
+
|
|
374
|
+
assert ma.isMA(data_)
|
|
375
|
+
|
|
376
|
+
logger.debug(
|
|
377
|
+
"data for column with offset %d was provided in dtype '%s', but need '%s': converting data...",
|
|
378
|
+
i,
|
|
379
|
+
data_.dtype,
|
|
380
|
+
dtype_,
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
logger.debug("dtype of data[%d] before: %s", i, data_.dtype)
|
|
384
|
+
logger.debug("type of data[%d] after: %s", i, type(data_))
|
|
385
|
+
logger.debug("size of data[%d] after: %s", i, ma.size(data_))
|
|
386
|
+
logger.debug("data of data[%d] after: %s", i, data_)
|
|
387
|
+
|
|
388
|
+
try:
|
|
389
|
+
data[i] = data_.astype(dtype_)
|
|
390
|
+
except TypeError as err:
|
|
391
|
+
# One 'bug' is that, if everything is masked, the underlying data type can be
|
|
392
|
+
# pretty much anything.
|
|
393
|
+
if _is_all_masked(data_):
|
|
394
|
+
logger.debug(
|
|
395
|
+
"array completely empty, re-initializing to empty array of '%s'",
|
|
396
|
+
dtype_,
|
|
397
|
+
)
|
|
398
|
+
data[i] = ma.masked_all(ma.size(data_), dtype=dtype_)
|
|
399
|
+
|
|
400
|
+
# Another 'bug' is that when the input data is objects, we may have null-like values (like pd.NA)
|
|
401
|
+
# that cannot easily be converted to, say, float.
|
|
402
|
+
else:
|
|
403
|
+
logger.error(
|
|
404
|
+
"An error occured while coercing input data type from dtype '%s' to dtype '%s': ",
|
|
405
|
+
data_.dtype,
|
|
406
|
+
dtype_,
|
|
407
|
+
)
|
|
408
|
+
logger.exception(err)
|
|
409
|
+
raise err
|
|
410
|
+
|
|
411
|
+
assert data[i].dtype.kind == dtype_.kind
|
|
412
|
+
|
|
413
|
+
logger.debug("type of data[%d] after: %s", i, type(data[i]))
|
|
414
|
+
logger.debug("size of data[%d] after: %s", i, ma.size(data[i]))
|
|
415
|
+
logger.debug("data of data[%d] after: %s", i, data[i])
|
|
416
|
+
assert ma.size(data[i]) == ma.size(data_)
|
|
417
|
+
|
|
418
|
+
return data
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def _probe_length(xs):
|
|
422
|
+
"""
|
|
423
|
+
Returns the length of the first non-null array in `xs`, or None if all arrays
|
|
424
|
+
are null.
|
|
425
|
+
"""
|
|
426
|
+
if isinstance(xs, dict):
|
|
427
|
+
return _probe_length(xs.values())
|
|
428
|
+
|
|
429
|
+
for x in xs:
|
|
430
|
+
if x is not None:
|
|
431
|
+
return x.size
|
|
432
|
+
|
|
433
|
+
return None
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _ensure_list(xs, cinfos):
|
|
437
|
+
"""
|
|
438
|
+
If input data is a dict, ensures it's converted to a list with the correct
|
|
439
|
+
offsets.
|
|
440
|
+
"""
|
|
441
|
+
if isinstance(xs, list):
|
|
442
|
+
return xs
|
|
443
|
+
|
|
444
|
+
if isinstance(xs, np.ndarray):
|
|
445
|
+
ret = []
|
|
446
|
+
for x in xs:
|
|
447
|
+
ret.append(x)
|
|
448
|
+
|
|
449
|
+
return ret
|
|
450
|
+
|
|
451
|
+
# As we only accept list-likes or dicts as input data, it *must* be a dict at this
|
|
452
|
+
# point
|
|
453
|
+
assert isinstance(xs, dict)
|
|
454
|
+
|
|
455
|
+
logger.debug("data was provided as dict, coercing to list")
|
|
456
|
+
|
|
457
|
+
# As we may have non-existing keys, we would like to initialize those as a masked
|
|
458
|
+
# array with all elements masked. In those cases, though, we need to know the size
|
|
459
|
+
# of the array.
|
|
460
|
+
n = _probe_length(xs)
|
|
461
|
+
|
|
462
|
+
if n is None:
|
|
463
|
+
logger.error("Unable to probe length: provided arrays: %s", xs)
|
|
464
|
+
raise ValueError("Unable to probe array length: all provided arrays None?")
|
|
465
|
+
|
|
466
|
+
ret = list()
|
|
467
|
+
|
|
468
|
+
for i in range(len(cinfos)):
|
|
469
|
+
(cname, ctype) = cinfos[i]
|
|
470
|
+
|
|
471
|
+
xs_ = None
|
|
472
|
+
if cname in xs:
|
|
473
|
+
xs_ = xs[cname]
|
|
474
|
+
else:
|
|
475
|
+
xs_ = ma.masked_all(n, dtype=_best_dtype_for_ctype(ctype))
|
|
476
|
+
|
|
477
|
+
ret.append(xs_)
|
|
478
|
+
|
|
479
|
+
return ret
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def _coerce_retries(retries) -> quasardb.RetryOptions:
|
|
483
|
+
if retries is None:
|
|
484
|
+
return quasardb.RetryOptions()
|
|
485
|
+
elif isinstance(retries, int):
|
|
486
|
+
return quasardb.RetryOptions(retries=retries)
|
|
487
|
+
elif isinstance(retries, quasardb.RetryOptions):
|
|
488
|
+
return retries
|
|
489
|
+
else:
|
|
490
|
+
raise TypeError(
|
|
491
|
+
"retries should either be an integer or quasardb.RetryOptions, got: "
|
|
492
|
+
+ type(retries)
|
|
493
|
+
)
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def _kwarg_deprecation_warning(
|
|
497
|
+
old_kwarg, old_value, new_kwargs, new_values, stacklevel
|
|
498
|
+
):
|
|
499
|
+
new_declaration = ", ".join(
|
|
500
|
+
f"{new_kwarg}={new_value}"
|
|
501
|
+
for new_kwarg, new_value in zip(new_kwargs, new_values)
|
|
502
|
+
)
|
|
503
|
+
warnings.warn(
|
|
504
|
+
f"The argument '{old_kwarg}' <{type(old_value).__name__}> is deprecated and will be removed in a future version. "
|
|
505
|
+
f"Please use '{new_declaration}' instead.",
|
|
506
|
+
DeprecationWarning,
|
|
507
|
+
stacklevel=stacklevel + 1,
|
|
508
|
+
)
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def _type_check(var, var_name, target_type, raise_error=True, allow_none=True):
|
|
512
|
+
if allow_none and var is None:
|
|
513
|
+
return True
|
|
514
|
+
if not isinstance(var, target_type):
|
|
515
|
+
if raise_error:
|
|
516
|
+
raise quasardb.quasardb.InvalidArgumentError(
|
|
517
|
+
f"Invalid '{var_name}' type, expected: {target_type}, got: {type(var)}"
|
|
518
|
+
)
|
|
519
|
+
return False
|
|
520
|
+
return True
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def ensure_ma(xs, dtype=None):
|
|
524
|
+
if isinstance(dtype, list):
|
|
525
|
+
assert isinstance(xs, list) == True
|
|
526
|
+
return [ensure_ma(xs_, dtype_) for (xs_, dtype_) in zip(xs, dtype)]
|
|
527
|
+
|
|
528
|
+
# Don't bother if we're already a masked array
|
|
529
|
+
if ma.isMA(xs):
|
|
530
|
+
return xs
|
|
531
|
+
|
|
532
|
+
if not isinstance(xs, np.ndarray):
|
|
533
|
+
logger.debug("Provided data is not a numpy array: %s", type(xs))
|
|
534
|
+
xs = np.array(xs, dtype=dtype)
|
|
535
|
+
|
|
536
|
+
logger.debug("coercing array with dtype: %s", xs.dtype)
|
|
537
|
+
|
|
538
|
+
if xs.dtype.kind in ["O", "U", "S"]:
|
|
539
|
+
logger.debug("Data is object-like, masking None values")
|
|
540
|
+
|
|
541
|
+
mask = xs == None
|
|
542
|
+
return ma.masked_array(data=xs, mask=mask)
|
|
543
|
+
else:
|
|
544
|
+
logger.debug("Automatically masking invalid numbers")
|
|
545
|
+
return ma.masked_invalid(xs, copy=False)
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def read_array(table=None, column=None, ranges=None):
|
|
549
|
+
if table is None:
|
|
550
|
+
raise RuntimeError("A table is required.")
|
|
551
|
+
|
|
552
|
+
if column is None:
|
|
553
|
+
raise RuntimeError("A column is required.")
|
|
554
|
+
|
|
555
|
+
kwargs = {"column": column}
|
|
556
|
+
|
|
557
|
+
if ranges is not None:
|
|
558
|
+
kwargs["ranges"] = ranges
|
|
559
|
+
|
|
560
|
+
read_with = {
|
|
561
|
+
quasardb.ColumnType.Double: table.double_get_ranges,
|
|
562
|
+
quasardb.ColumnType.Blob: table.blob_get_ranges,
|
|
563
|
+
quasardb.ColumnType.String: table.string_get_ranges,
|
|
564
|
+
quasardb.ColumnType.Symbol: table.string_get_ranges,
|
|
565
|
+
quasardb.ColumnType.Int64: table.int64_get_ranges,
|
|
566
|
+
quasardb.ColumnType.Timestamp: table.timestamp_get_ranges,
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
ctype = table.column_type_by_id(column)
|
|
570
|
+
|
|
571
|
+
fn = read_with[ctype]
|
|
572
|
+
return fn(**kwargs)
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def write_array(
|
|
576
|
+
data=None, index=None, table=None, column=None, dtype=None, infer_types=True
|
|
577
|
+
):
|
|
578
|
+
"""
|
|
579
|
+
Write a Numpy array to a single column.
|
|
580
|
+
|
|
581
|
+
Parameters:
|
|
582
|
+
-----------
|
|
583
|
+
|
|
584
|
+
data: np.array
|
|
585
|
+
Numpy array with a dtype that is compatible with the column's type.
|
|
586
|
+
|
|
587
|
+
index: np.array
|
|
588
|
+
Numpy array with a datetime64[ns] dtype that will be used as the
|
|
589
|
+
$timestamp axis for the data to be stored.
|
|
590
|
+
|
|
591
|
+
dtype: optional np.dtype
|
|
592
|
+
If provided, ensures the data array is converted to this dtype before
|
|
593
|
+
insertion.
|
|
594
|
+
|
|
595
|
+
infer_types: optional bool
|
|
596
|
+
If true, when necessary will attempt to convert the data and index array
|
|
597
|
+
to the best type for the column. For example, if you provide float64 data
|
|
598
|
+
while the column's type is int64, it will automatically convert the data.
|
|
599
|
+
|
|
600
|
+
Defaults to True. For production use cases where you want to avoid implicit
|
|
601
|
+
conversions, we recommend always setting this to False.
|
|
602
|
+
|
|
603
|
+
"""
|
|
604
|
+
|
|
605
|
+
if table is None:
|
|
606
|
+
raise RuntimeError("A table is required.")
|
|
607
|
+
|
|
608
|
+
if column is None:
|
|
609
|
+
raise RuntimeError("A column is required.")
|
|
610
|
+
|
|
611
|
+
if data is None:
|
|
612
|
+
raise RuntimeError("A data numpy array is required.")
|
|
613
|
+
|
|
614
|
+
if index is None:
|
|
615
|
+
raise RuntimeError("An index numpy timestamp array is required.")
|
|
616
|
+
|
|
617
|
+
data = ensure_ma(data, dtype=dtype)
|
|
618
|
+
ctype = table.column_type_by_id(column)
|
|
619
|
+
|
|
620
|
+
# We try to reuse some of the other functions, which assume array-like
|
|
621
|
+
# shapes for column info and data. It's a bit hackish, but actually works
|
|
622
|
+
# well.
|
|
623
|
+
#
|
|
624
|
+
# We should probably generalize this block of code with the same found in
|
|
625
|
+
# write_arrays().
|
|
626
|
+
|
|
627
|
+
cinfos = [(column, ctype)]
|
|
628
|
+
dtype_ = [dtype]
|
|
629
|
+
|
|
630
|
+
dtype = _coerce_dtype(dtype_, cinfos)
|
|
631
|
+
|
|
632
|
+
if infer_types is True:
|
|
633
|
+
dtype = _add_desired_dtypes(dtype, cinfos)
|
|
634
|
+
|
|
635
|
+
# data_ = an array of [data]
|
|
636
|
+
data_ = [data]
|
|
637
|
+
data_ = _coerce_data(data_, dtype)
|
|
638
|
+
_validate_dtypes(data_, cinfos)
|
|
639
|
+
|
|
640
|
+
# No functions that assume array-of-data anymore, let's put it back
|
|
641
|
+
data = data_[0]
|
|
642
|
+
|
|
643
|
+
# Dispatch to the correct function
|
|
644
|
+
write_with = {
|
|
645
|
+
quasardb.ColumnType.Double: table.double_insert,
|
|
646
|
+
quasardb.ColumnType.Blob: table.blob_insert,
|
|
647
|
+
quasardb.ColumnType.String: table.string_insert,
|
|
648
|
+
quasardb.ColumnType.Symbol: table.string_insert,
|
|
649
|
+
quasardb.ColumnType.Int64: table.int64_insert,
|
|
650
|
+
quasardb.ColumnType.Timestamp: table.timestamp_insert,
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
logger.info(
|
|
654
|
+
"Writing array (%d rows of dtype %s) to columns %s.%s (type %s)",
|
|
655
|
+
len(data),
|
|
656
|
+
data.dtype,
|
|
657
|
+
table.get_name(),
|
|
658
|
+
column,
|
|
659
|
+
ctype,
|
|
660
|
+
)
|
|
661
|
+
write_with[ctype](column, index, data)
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
def write_arrays(
|
|
665
|
+
data,
|
|
666
|
+
cluster,
|
|
667
|
+
table=None,
|
|
668
|
+
*,
|
|
669
|
+
dtype=None,
|
|
670
|
+
index=None,
|
|
671
|
+
# TODO: Set the default push_mode after removing _async, fast and truncate
|
|
672
|
+
push_mode=None,
|
|
673
|
+
_async=False,
|
|
674
|
+
fast=False,
|
|
675
|
+
truncate=False,
|
|
676
|
+
truncate_range=None,
|
|
677
|
+
deduplicate=False,
|
|
678
|
+
deduplication_mode="drop",
|
|
679
|
+
infer_types=True,
|
|
680
|
+
writer=None,
|
|
681
|
+
write_through=True,
|
|
682
|
+
retries=3,
|
|
683
|
+
# We accept additional kwargs that will be passed through the writer.push() methods
|
|
684
|
+
**kwargs,
|
|
685
|
+
):
|
|
686
|
+
"""
|
|
687
|
+
Write multiple aligned numpy arrays to a table.
|
|
688
|
+
|
|
689
|
+
Parameters:
|
|
690
|
+
-----------
|
|
691
|
+
|
|
692
|
+
data: Iterable of np.array, or dict-like of str:np.array
|
|
693
|
+
Numpy arrays to write into the database. Can either be a list of numpy arrays,
|
|
694
|
+
in which case they are expected to be in the same order as table.list_columns(),
|
|
695
|
+
and an array is provided for each of the columns. If `index` is None, the first
|
|
696
|
+
array will be assumed to be an index with dtype `datetime64[ns]`.
|
|
697
|
+
|
|
698
|
+
Alternatively, a dict of key/values may be provided, where the key is expected
|
|
699
|
+
to be a table column label, and the value is expected to be a np.array. If present,
|
|
700
|
+
a column with label '$timestamp' will be used as the index.
|
|
701
|
+
|
|
702
|
+
In all cases, all numpy arrays are expected to be of exactly the same length as the
|
|
703
|
+
index.
|
|
704
|
+
|
|
705
|
+
cluster: quasardb.Cluster
|
|
706
|
+
Active connection to the QuasarDB cluster
|
|
707
|
+
|
|
708
|
+
table: quasardb.Table or str
|
|
709
|
+
Either a string or a reference to a QuasarDB Timeseries table object.
|
|
710
|
+
For example, 'my_table' or cluster.table('my_table') are both valid values.
|
|
711
|
+
|
|
712
|
+
Defaults to False.
|
|
713
|
+
|
|
714
|
+
index: optional np.array with dtype datetime64[ns]
|
|
715
|
+
Optionally explicitly provide an array as the $timestamp index. If not provided,
|
|
716
|
+
the first array provided to `data` will be used as the index.
|
|
717
|
+
|
|
718
|
+
dtype: optional dtype, list of dtype, or dict of dtype
|
|
719
|
+
Optional data type to force. If a single dtype, will force that dtype to all
|
|
720
|
+
columns. If list-like, will map dtypes to dataframe columns by their offset.
|
|
721
|
+
If dict-like, will map dtypes to dataframe columns by their label.
|
|
722
|
+
|
|
723
|
+
If a dtype for a column is provided in this argument, and infer_types is also
|
|
724
|
+
True, this argument takes precedence.
|
|
725
|
+
|
|
726
|
+
deduplicate: bool or list[str]
|
|
727
|
+
Enables server-side deduplication of data when it is written into the table.
|
|
728
|
+
When True, automatically deduplicates rows when all values of a row are identical.
|
|
729
|
+
When a list of strings is provided, deduplicates only based on the values of
|
|
730
|
+
these columns.
|
|
731
|
+
|
|
732
|
+
Defaults to False.
|
|
733
|
+
|
|
734
|
+
deduplication_mode: 'drop' or 'upsert'
|
|
735
|
+
When `deduplicate` is enabled, decides how deduplication is performed. 'drop' means
|
|
736
|
+
any newly written duplicates are dropped, where 'upsert' means that the previously
|
|
737
|
+
written data is updated to reflect the new data.
|
|
738
|
+
|
|
739
|
+
Defaults to 'drop'.
|
|
740
|
+
|
|
741
|
+
infer_types: optional bool
|
|
742
|
+
If true, will attemp to convert types from Python to QuasarDB natives types if
|
|
743
|
+
the provided dataframe has incompatible types. For example, a dataframe with integers
|
|
744
|
+
will automatically convert these to doubles if the QuasarDB table expects it.
|
|
745
|
+
|
|
746
|
+
Defaults to True. For production use cases where you want to avoid implicit conversions,
|
|
747
|
+
we recommend setting this to False.
|
|
748
|
+
|
|
749
|
+
push_mode: optional quasardb.WriterPushMode
|
|
750
|
+
The mode used for inserting data. Can be either a string or a `WriterPushMode` enumeration item.
|
|
751
|
+
Available options:
|
|
752
|
+
* `Truncate`: Truncate (also referred to as upsert) the data in-place. Will detect time range
|
|
753
|
+
to truncate from the time range inside the dataframe.
|
|
754
|
+
* `Async`: Uses asynchronous insertion API where commits are buffered server-side and
|
|
755
|
+
acknowledged before they are written to disk. If you insert to the same table from
|
|
756
|
+
multiple processes, setting this to True may improve performance.
|
|
757
|
+
* `Fast`: Whether to use 'fast push'. If you incrementally add small batches of data to table,
|
|
758
|
+
you may see better performance if you set this to True.
|
|
759
|
+
* `Transactional`: Ensures full transactional consistency.
|
|
760
|
+
|
|
761
|
+
Defaults to `Transactional`.
|
|
762
|
+
|
|
763
|
+
truncate: optional bool
|
|
764
|
+
**DEPRECATED** – Use `push_mode=WriterPushMode.Truncate` instead.
|
|
765
|
+
Truncate (also referred to as upsert) the data in-place. Will detect time range to truncate
|
|
766
|
+
from the time range inside the dataframe.
|
|
767
|
+
|
|
768
|
+
Defaults to False.
|
|
769
|
+
|
|
770
|
+
truncate_range: optional tuple
|
|
771
|
+
Time range to truncate from the time range inside the dataframe.
|
|
772
|
+
|
|
773
|
+
_async: optional bool
|
|
774
|
+
**DEPRECATED** – Use `push_mode=WriterPushMode.Async` instead.
|
|
775
|
+
If true, uses asynchronous insertion API where commits are buffered server-side and
|
|
776
|
+
acknowledged before they are written to disk. If you insert to the same table from
|
|
777
|
+
multiple processes, setting this to True may improve performance.
|
|
778
|
+
|
|
779
|
+
Defaults to False.
|
|
780
|
+
|
|
781
|
+
fast: optional bool
|
|
782
|
+
**DEPRECATED** – Use `push_mode=WriterPushMode.Fast` instead.
|
|
783
|
+
Whether to use 'fast push'. If you incrementally add small batches of data to table,
|
|
784
|
+
you may see better performance if you set this to True.
|
|
785
|
+
|
|
786
|
+
Defaults to False.
|
|
787
|
+
|
|
788
|
+
write_through: optional bool
|
|
789
|
+
If True, data is not cached after write.
|
|
790
|
+
By default is False, in which case caching is left at the discretion of the server.
|
|
791
|
+
|
|
792
|
+
writer: optional quasardb.Writer
|
|
793
|
+
Allows you to explicitly provide a Writer to use, which is expected to be
|
|
794
|
+
initialized with the `table`.
|
|
795
|
+
|
|
796
|
+
Reuse of the Writer allows for some performance improvements.
|
|
797
|
+
|
|
798
|
+
retries: optional int or quasardb.RetryOptions
|
|
799
|
+
Number of times to retry in case of a push failure. This is useful in case of async
|
|
800
|
+
pipeline failures, or when doing transactional inserts that may occasionally cause
|
|
801
|
+
transaction conflicts.
|
|
802
|
+
|
|
803
|
+
Retries with exponential backoff, starts at 3 seconds, and doubles every retry attempt.
|
|
804
|
+
|
|
805
|
+
Alternatively, a quasardb.RetryOptions object can be passed to more carefully fine-tune
|
|
806
|
+
retry behavior.
|
|
807
|
+
"""
|
|
808
|
+
|
|
809
|
+
if table:
|
|
810
|
+
logger.debug("table explicitly provided, assuming single-table write")
|
|
811
|
+
data = [(table, data)]
|
|
812
|
+
table = None
|
|
813
|
+
|
|
814
|
+
_type_check(push_mode, "push_mode", target_type=quasardb.WriterPushMode)
|
|
815
|
+
deprecation_stacklevel = kwargs.pop("deprecation_stacklevel", 1) + 1
|
|
816
|
+
|
|
817
|
+
if isinstance(truncate, tuple):
|
|
818
|
+
# Especial case, truncate might be a tuple indicating the range.
|
|
819
|
+
_kwarg_deprecation_warning(
|
|
820
|
+
"truncate",
|
|
821
|
+
truncate,
|
|
822
|
+
["push_mode", "truncate_range"],
|
|
823
|
+
[quasardb.WriterPushMode.Truncate, truncate],
|
|
824
|
+
deprecation_stacklevel,
|
|
825
|
+
)
|
|
826
|
+
truncate_range = truncate_range or truncate
|
|
827
|
+
truncate = True
|
|
828
|
+
|
|
829
|
+
kwarg_to_mode = {
|
|
830
|
+
# "kwarg": (kwarg_type, kwarg_push_mode, is_deprecated)
|
|
831
|
+
"fast": (bool, quasardb.WriterPushMode.Fast, True),
|
|
832
|
+
"_async": (bool, quasardb.WriterPushMode.Async, True),
|
|
833
|
+
"truncate": (bool, quasardb.WriterPushMode.Truncate, True),
|
|
834
|
+
"truncate_range": (tuple, quasardb.WriterPushMode.Truncate, False),
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
for kwarg, info in kwarg_to_mode.items():
|
|
838
|
+
expected_type, mode, deprecated = info
|
|
839
|
+
kwarg_value = locals()[kwarg]
|
|
840
|
+
_type_check(kwarg_value, kwarg, target_type=expected_type)
|
|
841
|
+
|
|
842
|
+
if kwarg_value:
|
|
843
|
+
if push_mode and push_mode != mode:
|
|
844
|
+
raise quasardb.quasardb.InvalidArgumentError(
|
|
845
|
+
f"Found '{kwarg}' in kwargs, but push mode is already set to {push_mode}"
|
|
846
|
+
)
|
|
847
|
+
push_mode = mode
|
|
848
|
+
if deprecated:
|
|
849
|
+
_kwarg_deprecation_warning(
|
|
850
|
+
kwarg, kwarg_value, ["push_mode"], [mode], deprecation_stacklevel
|
|
851
|
+
)
|
|
852
|
+
|
|
853
|
+
if not push_mode:
|
|
854
|
+
push_mode = quasardb.WriterPushMode.Transactional
|
|
855
|
+
|
|
856
|
+
# Create batch column info from dataframe
|
|
857
|
+
if writer is None:
|
|
858
|
+
writer = cluster.writer()
|
|
859
|
+
|
|
860
|
+
ret = []
|
|
861
|
+
n_rows = 0
|
|
862
|
+
push_data = quasardb.WriterData()
|
|
863
|
+
|
|
864
|
+
for table, data_ in data:
|
|
865
|
+
# Acquire reference to table if string is provided
|
|
866
|
+
if isinstance(table, str):
|
|
867
|
+
table = table_cache.lookup(table, cluster)
|
|
868
|
+
|
|
869
|
+
cinfos = [(x.name, x.type) for x in table.list_columns()]
|
|
870
|
+
dtype = _coerce_dtype(dtype, cinfos)
|
|
871
|
+
|
|
872
|
+
assert type(dtype) is list
|
|
873
|
+
assert len(dtype) is len(cinfos)
|
|
874
|
+
|
|
875
|
+
if index is None and isinstance(data_, dict) and "$timestamp" in data_:
|
|
876
|
+
# Create shallow copy of `data_` so that we don't modify the reference, i.e.
|
|
877
|
+
# delete keys.
|
|
878
|
+
#
|
|
879
|
+
# This ensures that the user can call the same function multiple times without
|
|
880
|
+
# side-effects.
|
|
881
|
+
data_ = data_.copy()
|
|
882
|
+
index_ = data_.pop("$timestamp")
|
|
883
|
+
assert "$timestamp" not in data_
|
|
884
|
+
elif index is not None:
|
|
885
|
+
index_ = index
|
|
886
|
+
else:
|
|
887
|
+
raise RuntimeError("Invalid index: no index provided.")
|
|
888
|
+
|
|
889
|
+
assert index_ is not None
|
|
890
|
+
|
|
891
|
+
if infer_types is True:
|
|
892
|
+
dtype = _add_desired_dtypes(dtype, cinfos)
|
|
893
|
+
|
|
894
|
+
data_ = _ensure_list(data_, cinfos)
|
|
895
|
+
|
|
896
|
+
if len(data_) != len(cinfos):
|
|
897
|
+
raise InvalidDataCardinalityError(data_, cinfos)
|
|
898
|
+
|
|
899
|
+
data_ = ensure_ma(data_, dtype=dtype)
|
|
900
|
+
data_ = _coerce_data(data_, dtype)
|
|
901
|
+
|
|
902
|
+
# Just some additional friendly information about incorrect dtypes, we'd
|
|
903
|
+
# prefer to have this information thrown from Python instead of native
|
|
904
|
+
# code as it generally makes for somewhat better error context.
|
|
905
|
+
_validate_dtypes(data_, cinfos)
|
|
906
|
+
|
|
907
|
+
deduplicate = _coerce_deduplicate(deduplicate, deduplication_mode, cinfos)
|
|
908
|
+
|
|
909
|
+
# Sanity check
|
|
910
|
+
assert len(data_) == len(cinfos)
|
|
911
|
+
|
|
912
|
+
for i in range(len(data_)):
|
|
913
|
+
assert len(data_[i]) == len(index_)
|
|
914
|
+
|
|
915
|
+
push_data.append(table, index_, data_)
|
|
916
|
+
|
|
917
|
+
n_rows += len(index_)
|
|
918
|
+
ret.append(table)
|
|
919
|
+
|
|
920
|
+
retries = _coerce_retries(retries)
|
|
921
|
+
|
|
922
|
+
# By default, we push all additional kwargs to the writer.push() function. This allows transparent propagation
|
|
923
|
+
# arguments.
|
|
924
|
+
#
|
|
925
|
+
# The initial use case was that so we can add additional parameters for test mocks, e.g. `mock_failures` so that
|
|
926
|
+
# we can validate the retry functionality.
|
|
927
|
+
push_kwargs = kwargs
|
|
928
|
+
push_kwargs["deduplicate"] = deduplicate
|
|
929
|
+
push_kwargs["deduplication_mode"] = deduplication_mode
|
|
930
|
+
push_kwargs["write_through"] = write_through
|
|
931
|
+
push_kwargs["retries"] = retries
|
|
932
|
+
push_kwargs["push_mode"] = push_mode
|
|
933
|
+
if truncate_range:
|
|
934
|
+
push_kwargs["range"] = truncate_range
|
|
935
|
+
|
|
936
|
+
logger.debug("pushing %d rows", n_rows)
|
|
937
|
+
start = time.time()
|
|
938
|
+
|
|
939
|
+
writer.push(push_data, **push_kwargs)
|
|
940
|
+
|
|
941
|
+
logger.debug("pushed %d rows in %s seconds", n_rows, (time.time() - start))
|
|
942
|
+
|
|
943
|
+
return ret
|
|
944
|
+
|
|
945
|
+
|
|
946
|
+
def _xform_query_results(xs, index, dict):
|
|
947
|
+
if len(xs) == 0:
|
|
948
|
+
return (np.array([], np.dtype("datetime64[ns]")), np.array([]))
|
|
949
|
+
|
|
950
|
+
n = None
|
|
951
|
+
for x in xs:
|
|
952
|
+
assert isinstance(x, tuple)
|
|
953
|
+
|
|
954
|
+
if n is None:
|
|
955
|
+
n = x[1].size
|
|
956
|
+
else:
|
|
957
|
+
assert x[1].size == n
|
|
958
|
+
|
|
959
|
+
if index is None:
|
|
960
|
+
# Generate a range, put it in the front of the result list,
|
|
961
|
+
# recurse and tell the function to use that index.
|
|
962
|
+
xs_ = [("$index", np.arange(n))] + xs
|
|
963
|
+
return _xform_query_results(xs_, "$index", dict)
|
|
964
|
+
|
|
965
|
+
if isinstance(index, str):
|
|
966
|
+
for i in range(len(xs)):
|
|
967
|
+
(cname, _) = xs[i]
|
|
968
|
+
if cname == index:
|
|
969
|
+
# Now we know that this column has offset `i`,
|
|
970
|
+
# recurse with that offset
|
|
971
|
+
return _xform_query_results(xs, i, dict)
|
|
972
|
+
|
|
973
|
+
raise KeyError(
|
|
974
|
+
"Unable to resolve index column: column not found in results: {}".format(
|
|
975
|
+
index
|
|
976
|
+
)
|
|
977
|
+
)
|
|
978
|
+
|
|
979
|
+
if not isinstance(index, int):
|
|
980
|
+
raise TypeError(
|
|
981
|
+
"Unable to resolve index column: unrecognized type {}: {}".format(
|
|
982
|
+
type(index), index
|
|
983
|
+
)
|
|
984
|
+
)
|
|
985
|
+
|
|
986
|
+
idx = xs[index][1]
|
|
987
|
+
del xs[index]
|
|
988
|
+
|
|
989
|
+
# Our index *may* be a masked array, but if it is, there should be no
|
|
990
|
+
# masked items: we cannot not have an index for a certain row.
|
|
991
|
+
if ma.isMA(idx):
|
|
992
|
+
if ma.count_masked(idx) > 0:
|
|
993
|
+
raise ValueError(
|
|
994
|
+
"Invalid index: null values detected. An index is never allowed to have null values."
|
|
995
|
+
)
|
|
996
|
+
|
|
997
|
+
assert isinstance(idx.data, np.ndarray)
|
|
998
|
+
idx = idx.data
|
|
999
|
+
|
|
1000
|
+
xs_ = None
|
|
1001
|
+
|
|
1002
|
+
if dict is True:
|
|
1003
|
+
xs_ = {x[0]: x[1] for x in xs}
|
|
1004
|
+
else:
|
|
1005
|
+
xs_ = [x[1] for x in xs]
|
|
1006
|
+
|
|
1007
|
+
return (idx, xs_)
|
|
1008
|
+
|
|
1009
|
+
|
|
1010
|
+
def query(cluster, query, index=None, dict=False):
|
|
1011
|
+
"""
|
|
1012
|
+
Execute a query and return the results as numpy arrays. The shape of the return value
|
|
1013
|
+
is always:
|
|
1014
|
+
|
|
1015
|
+
tuple[index, dict | list[np.array]]
|
|
1016
|
+
|
|
1017
|
+
|
|
1018
|
+
If `dict` is True, constructs a dict[str, np.array] where the key is the column name.
|
|
1019
|
+
Otherwise, it returns a list of all the individual data arrays.
|
|
1020
|
+
|
|
1021
|
+
|
|
1022
|
+
|
|
1023
|
+
Parameters:
|
|
1024
|
+
-----------
|
|
1025
|
+
|
|
1026
|
+
cluster : quasardb.Cluster
|
|
1027
|
+
Active connection to the QuasarDB cluster
|
|
1028
|
+
|
|
1029
|
+
query : str
|
|
1030
|
+
The query to execute.
|
|
1031
|
+
|
|
1032
|
+
index : optional[str | int]
|
|
1033
|
+
If provided, resolves column and uses that as the index. If string (e.g. `$timestamp`), uses
|
|
1034
|
+
that column as the index. If int (e.g. `1`), looks up the column based on that offset.
|
|
1035
|
+
|
|
1036
|
+
dict : bool
|
|
1037
|
+
If true, returns data arrays as a dict, otherwise a list of np.arrays.
|
|
1038
|
+
Defaults to False.
|
|
1039
|
+
|
|
1040
|
+
"""
|
|
1041
|
+
|
|
1042
|
+
m = {}
|
|
1043
|
+
xs = cluster.query_numpy(query)
|
|
1044
|
+
|
|
1045
|
+
return _xform_query_results(xs, index, dict)
|