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