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