quasardb 3.14.2.dev6__cp37-cp37m-manylinux_2_27_x86_64.manylinux_2_28_x86_64.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.

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