-
Notifications
You must be signed in to change notification settings - Fork 7
/
query.go
1412 lines (1191 loc) · 45.8 KB
/
query.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package tiledb
/*
#include <tiledb/tiledb.h>
#include <stdlib.h>
*/
import "C"
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"sync"
"unsafe"
"github.com/TileDB-Inc/TileDB-Go/bytesizes"
)
// Query construct and execute read/write queries on a tiledb Array
type Query struct {
tiledbQuery *C.tiledb_query_t
array *Array
context *Context
config *Config
buffers []interface{}
bufferMutex sync.Mutex
resultBufferElements map[string][3]*uint64
}
// RangeLimits defines a query range
type RangeLimits struct {
start interface{}
end interface{}
}
// MarshalJSON implements the Marshaler interface for RangeLimits.
func (r RangeLimits) MarshalJSON() ([]byte, error) {
rangeLimitMap := make(map[string]interface{})
rangeLimitMap["end"] = r.end
rangeLimitMap["start"] = r.start
return json.Marshal(rangeLimitMap)
}
/*
NewQuery creates a TileDB query object.
If the provided Context is nil, the context of the Array is used instead.
The storage manager also acquires a shared lock on the array.
This means multiple read and write queries to the same array can be made
concurrently (in TileDB, only consolidation requires an exclusive lock for
a short period of time).
*/
func NewQuery(tdbCtx *Context, array *Array) (*Query, error) {
if array == nil {
return nil, fmt.Errorf("Error creating tiledb query: passed array is nil")
}
if tdbCtx == nil {
tdbCtx = array.context
}
queryType, err := array.QueryType()
if err != nil {
return nil, fmt.Errorf("Error getting QueryType from passed array %s", err)
}
query := Query{context: tdbCtx, array: array}
ret := C.tiledb_query_alloc(query.context.tiledbContext, array.tiledbArray, C.tiledb_query_type_t(queryType), &query.tiledbQuery)
if ret != C.TILEDB_OK {
return nil, fmt.Errorf("Error creating tiledb query: %s", query.context.LastError())
}
freeOnGC(&query)
query.resultBufferElements = make(map[string][3]*uint64)
return &query, nil
}
// Free releases the internal TileDB core data that was allocated on the C heap.
// It is automatically called when this object is garbage collected, but can be
// called earlier to manually release memory if needed. Free is idempotent and
// can safely be called many times on the same object; if it has already
// been freed, it will not be freed again.
func (q *Query) Free() {
q.bufferMutex.Lock()
defer q.bufferMutex.Unlock()
q.buffers = nil
q.resultBufferElements = nil
if q.tiledbQuery != nil {
C.tiledb_query_free(&q.tiledbQuery)
}
}
// Context exposes the internal TileDB context used to initialize the query.
func (q *Query) Context() *Context {
return q.context
}
// GetRanges gets the number of dimensions from the array under current query
// and builds an array of dimensions that have as memmbers arrays of ranges.
//
// Deprecated: Use Subarrays
func (q *Query) GetRanges() (map[string][]RangeLimits, error) {
// We need to infer the datatype of the dimension represented by index
// dimIdx. That said:
// Get array schema
schema, err := q.array.Schema()
if err != nil {
return nil, err
}
// Get the domain object
domain, err := schema.Domain()
if err != nil {
return nil, err
}
// Use the index to retrieve the dimension object
nDim, err := domain.NDim()
if err != nil {
return nil, err
}
subarray, err := q.GetSubarray()
if err != nil {
return nil, err
}
var dimIdx uint
rangeMap := make(map[string][]RangeLimits)
for dimIdx = 0; dimIdx < nDim; dimIdx++ {
// Get dimension object
dimension, err := domain.DimensionFromIndex(dimIdx)
if err != nil {
return nil, err
}
// Get name from dimension
name, err := dimension.Name()
if err != nil {
return nil, err
}
// Get number of renges to iterate
numOfRanges, err := subarray.GetRangeNum(uint32(dimIdx))
if err != nil {
return nil, err
}
var I uint64
rangeArray := make([]RangeLimits, 0)
for I = 0; I < numOfRanges; I++ {
r, err := subarray.GetRange(uint32(dimIdx), I)
if err != nil {
return nil, err
}
// Append range to range Array
rangeArray = append(rangeArray, RangeLimits(r))
}
// key: name (string), value: rangeArray ([]RangeLimits)
rangeMap[name] = rangeArray
}
return rangeMap, err
}
// ResultBufferElements returns the number of elements in the result buffers
// from a read query.
// This is a map from the attribute name to a pair of values.
// The first is number of elements (offsets) for var size attributes, and the
// second is number of elements in the data buffer. For fixed sized attributes
// (and coordinates), the first is always 0.
func (q *Query) ResultBufferElements() (map[string][3]uint64, error) {
elements := make(map[string][3]uint64)
// Will need the schema to infer data type size for attributes
schema, err := q.array.Schema()
if err != nil {
return nil, fmt.Errorf("Could not get schema for ResultBufferElements: %s", err)
}
defer schema.Free()
domain, err := schema.Domain()
if err != nil {
return nil, fmt.Errorf("Could not get domain for ResultBufferElements: %s", err)
}
defer domain.Free()
var datatype Datatype
for attributeOrDimension, v := range q.resultBufferElements {
// Handle coordinates
if attributeOrDimension == TILEDB_COORDS {
// For fixed length attributes offset elements are always zero
offsetElements := uint64(0)
domainType, err := domain.Type()
if err != nil {
return nil, fmt.Errorf("Could not get domainType for ResultBufferElements: %s", err)
}
// Number of buffer elements is calculated
bufferElements := (*v[1]) / domainType.Size()
elements[attributeOrDimension] = [3]uint64{offsetElements, bufferElements, 0}
} else {
// For fixed length attributes offset elements are always zero
offsetElements := uint64(0)
if v[0] != nil {
// The attribute is variable length
offsetElements = (*v[0]) / bytesizes.Uint64
}
validityElements := uint64(0)
if v[2] != nil {
// The attribute is nullable
validityElements = (*v[2]) / bytesizes.Uint8
}
hasDim, err := domain.HasDimension(attributeOrDimension)
if err != nil {
return nil, err
}
hasAttr, err := schema.HasAttribute(attributeOrDimension)
if err != nil {
return nil, err
}
hasDimLabel, err := schema.HasDimensionLabel(attributeOrDimension)
if err != nil {
return nil, err
}
if hasDim {
dimension, err := domain.DimensionFromName(attributeOrDimension)
if err != nil {
return nil, fmt.Errorf("Could not get attribute or dimension for SetBuffer: %s", attributeOrDimension)
}
datatype, err = dimension.Type()
if err != nil {
return nil, fmt.Errorf("Could not get dimensionType for SetBuffer: %s", attributeOrDimension)
}
dimension.Free()
} else if hasAttr {
// Get the attribute
attribute, err := schema.AttributeFromName(attributeOrDimension)
if err != nil {
return nil, fmt.Errorf("Could not get attribute %s for ResultBufferElements: %s", attributeOrDimension, err)
}
// Get datatype size to convert byte lengths to needed buffer sizes
datatype, err = attribute.Type()
if err != nil {
return nil, fmt.Errorf("Could not get attribute type for ResultBufferElements: %s", err)
}
attribute.Free()
} else if hasDimLabel {
datatype, err = q.getDimensionLabelDataType(attributeOrDimension)
if err != nil {
return nil, fmt.Errorf("Could not get dimension label type for ResultBufferElements: %s", err)
}
} else {
return nil, fmt.Errorf("Error in ResultBufferElements for %s: "+
"Attribute/dimension/label does not exist.", attributeOrDimension)
}
// Number of buffer elements is calculated
bufferElements := (*v[1]) / datatype.Size()
elements[attributeOrDimension] = [3]uint64{offsetElements, bufferElements, validityElements}
}
}
return elements, nil
}
// SetLayout sets the layout of the cells to be written or read.
func (q *Query) SetLayout(layout Layout) error {
ret := C.tiledb_query_set_layout(q.context.tiledbContext, q.tiledbQuery, C.tiledb_layout_t(layout))
if ret != C.TILEDB_OK {
return fmt.Errorf("Error setting query layout: %s", q.context.LastError())
}
return nil
}
// SetQueryCondition sets a query condition on a read query.
func (q *Query) SetQueryCondition(cond *QueryCondition) error {
if ret := C.tiledb_query_set_condition(q.context.tiledbContext, q.tiledbQuery, cond.cond); ret != C.TILEDB_OK {
return fmt.Errorf("Error getting config from query: %s", q.context.LastError())
}
return nil
}
// Finalize flushes all internal state of a query object and finalizes the
// query. This is applicable only to global layout writes. It has no effect
// for any other query type.
func (q *Query) Finalize() error {
ret := C.tiledb_query_finalize(q.context.tiledbContext, q.tiledbQuery)
if ret != C.TILEDB_OK {
return fmt.Errorf("Error finalizing query: %s", q.context.LastError())
}
q.bufferMutex.Lock()
defer q.bufferMutex.Unlock()
q.buffers = nil
return nil
}
/*
Submit a TileDB query
This will block until query is completed
Note:
Finalize() must be invoked after finish writing in global layout
(via repeated invocations of Submit()), in order to flush any internal state.
For the case of reads, if the returned status is TILEDB_INCOMPLETE, TileDB
could not fit the entire result in the user’s buffers. In this case, the user
should consume the read results (if any), optionally reset the buffers with
SetBuffer(), and then resubmit the query until the status becomes
TILEDB_COMPLETED. If all buffer sizes after the termination of this
function become 0, then this means that no useful data was read into
the buffers, implying that the larger buffers are needed for the query
to proceed. In this case, the users must reallocate their buffers
(increasing their size), reset the buffers with set_buffer(),
and resubmit the query.
*/
func (q *Query) Submit() error {
ret := C.tiledb_query_submit(q.context.tiledbContext, q.tiledbQuery)
if ret != C.TILEDB_OK {
return fmt.Errorf("Error submitting query: %s", q.context.LastError())
}
return nil
}
// Status returns the status of a query.
func (q *Query) Status() (QueryStatus, error) {
var status C.tiledb_query_status_t
ret := C.tiledb_query_get_status(q.context.tiledbContext, q.tiledbQuery, &status)
if ret != C.TILEDB_OK {
return -1, fmt.Errorf("Error getting query status: %s", q.context.LastError())
}
return QueryStatus(status), nil
}
// Type returns the query type.
func (q *Query) Type() (QueryType, error) {
var queryType C.tiledb_query_type_t
ret := C.tiledb_query_get_type(q.context.tiledbContext, q.tiledbQuery, &queryType)
if ret != C.TILEDB_OK {
return -1, fmt.Errorf("Error getting query type: %s", q.context.LastError())
}
return QueryType(queryType), nil
}
// HasResults returns true if the query has results.
// Applicable only to read queries (it returns false for write queries).
func (q *Query) HasResults() (bool, error) {
var hasResults C.int32_t
ret := C.tiledb_query_has_results(q.context.tiledbContext, q.tiledbQuery, &hasResults)
if ret != C.TILEDB_OK {
return false, fmt.Errorf("Error checking if query has results: %s", q.context.LastError())
}
return int(hasResults) == 1, nil
}
// EstResultSize gets the query estimated result size in bytes for an attribute.
func (q *Query) EstResultSize(attributeName string) (*uint64, error) {
cAttributeName := C.CString(attributeName)
defer C.free(unsafe.Pointer(cAttributeName))
var size uint64
ret := C.tiledb_query_get_est_result_size(
q.context.tiledbContext,
q.tiledbQuery,
cAttributeName,
(*C.uint64_t)(unsafe.Pointer(&size)))
if ret != C.TILEDB_OK {
return nil, fmt.Errorf("Error estimating query result size: %s", q.context.LastError())
}
return &size, nil
}
// EstResultSizeVar gets the query estimated result size in bytes for a var sized attribute.
func (q *Query) EstResultSizeVar(attributeName string) (*uint64, *uint64, error) {
cAttributeName := C.CString(attributeName)
defer C.free(unsafe.Pointer(cAttributeName))
var sizeOff, sizeVal uint64
ret := C.tiledb_query_get_est_result_size_var(
q.context.tiledbContext,
q.tiledbQuery,
cAttributeName,
(*C.uint64_t)(unsafe.Pointer(&sizeOff)),
(*C.uint64_t)(unsafe.Pointer(&sizeVal)))
if ret != C.TILEDB_OK {
return nil, nil, fmt.Errorf("Error estimating query result var size: %s", q.context.LastError())
}
return &sizeOff, &sizeVal, nil
}
// EstResultSizeNullable gets the query estimated result size in bytes for an attribute.
func (q *Query) EstResultSizeNullable(attributeName string) (*uint64, *uint64, error) {
cAttributeName := C.CString(attributeName)
defer C.free(unsafe.Pointer(cAttributeName))
var size, sizeValidity uint64
ret := C.tiledb_query_get_est_result_size_nullable(
q.context.tiledbContext,
q.tiledbQuery,
cAttributeName,
(*C.uint64_t)(unsafe.Pointer(&size)),
(*C.uint64_t)(unsafe.Pointer(&sizeValidity)))
if ret != C.TILEDB_OK {
return nil, nil, fmt.Errorf("Error estimating query result size: %s", q.context.LastError())
}
return &size, &sizeValidity, nil
}
// EstResultSizeVarNullable gets the query estimated result size in bytes for a var sized attribute.
func (q *Query) EstResultSizeVarNullable(attributeName string) (*uint64, *uint64, *uint64, error) {
cAttributeName := C.CString(attributeName)
defer C.free(unsafe.Pointer(cAttributeName))
var sizeOff, sizeVal, sizeValidity uint64
ret := C.tiledb_query_get_est_result_size_var_nullable(
q.context.tiledbContext,
q.tiledbQuery,
cAttributeName,
(*C.uint64_t)(unsafe.Pointer(&sizeOff)),
(*C.uint64_t)(unsafe.Pointer(&sizeVal)),
(*C.uint64_t)(unsafe.Pointer(&sizeValidity)))
if ret != C.TILEDB_OK {
return nil, nil, nil, fmt.Errorf("Error estimating query result var size: %s", q.context.LastError())
}
return &sizeOff, &sizeVal, &sizeValidity, nil
}
/*
EstimateBufferElements computes an upper bound on the buffer elements needed to
read a subarray or range(s).
Returns a map of attribute or dimension name to the maximum
number of elements that can be read in the given subarray. For each attribute,
a pair of numbers are returned. The first, for variable-length attributes, is
the maximum number of offsets for that attribute in the given subarray. For
fixed-length attributes and coordinates, the first is always 0. The second
is the maximum number of elements for that attribute in the given subarray.
*/
func (q *Query) EstimateBufferElements() (map[string][3]uint64, error) {
// Build map
ret := make(map[string][3]uint64)
// Get schema
schema, err := q.array.Schema()
if err != nil {
return nil, fmt.Errorf("Error getting EstimateBufferElements for array: %s", err)
}
defer schema.Free()
attributes, err := schema.Attributes()
if err != nil {
return nil, fmt.Errorf("Error getting EstimateBufferElements for array: %s", err)
}
// Loop through each attribute
for _, attribute := range attributes {
// Wrap the body of the for loop in a function to be sure resources are freed by defer calls.
err := func() error {
defer attribute.Free()
// Check if attribute is variable attribute or not
cellValNum, err := attribute.CellValNum()
if err != nil {
return fmt.Errorf("Error getting EstimateBufferElements for array: %s", err)
}
// Get datatype size to convert byte lengths to needed buffer sizes
dataType, err := attribute.Type()
if err != nil {
return fmt.Errorf("Error getting EstimateBufferElements for array: %s", err)
}
dataTypeSize := dataType.Size()
// Get attribute name
name, err := attribute.Name()
if err != nil {
return fmt.Errorf("Error getting EstimateBufferElements for array: %s", err)
}
nullable, err := attribute.Nullable()
if err != nil {
return fmt.Errorf("Error getting EstimateBufferElements for array: %s", err)
}
if cellValNum == TILEDB_VAR_NUM {
if nullable {
bufferOffsetSize, bufferValSize, bufferValiditySize, err := q.EstResultSizeVarNullable(name)
if err != nil {
return fmt.Errorf("Error getting EstimateBufferElements for array: %s", err)
}
// Set sizes for attribute in return map
ret[name] = [3]uint64{
*bufferOffsetSize / uint64(C.TILEDB_OFFSET_SIZE),
*bufferValSize / dataTypeSize,
*bufferValiditySize / bytesizes.Uint8}
} else {
bufferOffsetSize, bufferValSize, err := q.EstResultSizeVar(name)
if err != nil {
return fmt.Errorf("Error getting EstimateBufferElements for array: %s", err)
}
// Set sizes for attribute in return map
ret[name] = [3]uint64{
*bufferOffsetSize / uint64(C.TILEDB_OFFSET_SIZE),
*bufferValSize / dataTypeSize,
0}
}
} else {
if nullable {
bufferValSize, bufferValiditySize, err := q.EstResultSizeNullable(name)
if err != nil {
return fmt.Errorf("Error getting EstimateBufferElements for array: %s", err)
}
ret[name] = [3]uint64{0, *bufferValSize / dataTypeSize,
*bufferValiditySize / bytesizes.Uint8}
} else {
bufferValSize, err := q.EstResultSize(name)
if err != nil {
return fmt.Errorf("Error getting EstimateBufferElements for array: %s", err)
}
ret[name] = [3]uint64{0, *bufferValSize / dataTypeSize, 0}
}
}
return nil
}()
if err != nil {
return nil, err
}
}
// Handle coordinates
domain, err := schema.Domain()
if err != nil {
return nil, fmt.Errorf("Could not get domain for EstimateBufferElements: %s", err)
}
defer domain.Free()
ndims, err := domain.NDim()
if err != nil {
return nil, err
}
for dimIdx := uint(0); dimIdx < ndims; dimIdx++ {
err = func() error {
dim, err := domain.DimensionFromIndex(dimIdx)
if err != nil {
return err
}
defer dim.Free()
dimType, err := dim.Type()
if err != nil {
return err
}
dataTypeSize := dimType.Size()
cellValNum, err := dim.CellValNum()
if err != nil {
return fmt.Errorf("Error getting MaxBufferElements for array: %s", err)
}
// Get dimension name
name, err := dim.Name()
if err != nil {
return fmt.Errorf("Error getting MaxBufferElements for array: %s", err)
}
if cellValNum == TILEDB_VAR_NUM {
bufferOffsetSize, bufferValSize, err := q.EstResultSizeVar(name)
if err != nil {
return fmt.Errorf("Error getting MaxBufferElements for array: %s", err)
}
// Set sizes for dimension in return map
ret[name] = [3]uint64{
*bufferOffsetSize / uint64(C.TILEDB_OFFSET_SIZE),
*bufferValSize / dataTypeSize, 0}
} else {
bufferValSize, err := q.EstResultSize(name)
if err != nil {
return fmt.Errorf("Error getting MaxBufferElements for array: %s", err)
}
ret[name] = [3]uint64{0, *bufferValSize / dataTypeSize, 0}
}
return nil
}()
if err != nil {
return nil, err
}
}
return ret, nil
}
// GetFragmentNum returns num of fragments.
func (q *Query) GetFragmentNum() (*uint32, error) {
var num uint32
ret := C.tiledb_query_get_fragment_num(
q.context.tiledbContext,
q.tiledbQuery,
(*C.uint32_t)(unsafe.Pointer(&num)))
if ret != C.TILEDB_OK {
return nil, fmt.Errorf("Error getting num of fragments: %s", q.context.LastError())
}
return &num, nil
}
// GetFragmentURI returns the uri for a fragment.
func (q *Query) GetFragmentURI(num uint64) (*string, error) {
var cURI *C.char
ret := C.tiledb_query_get_fragment_uri(
q.context.tiledbContext,
q.tiledbQuery,
(C.uint64_t)(num),
&cURI)
if ret != C.TILEDB_OK {
return nil, fmt.Errorf("Error uri for fragment : %d", q.context.LastError())
}
uri := C.GoString(cURI)
return &uri, nil
}
// GetFragmentTimestampRange returns timestamp range for a fragment.
func (q *Query) GetFragmentTimestampRange(num uint64) (*uint64, *uint64, error) {
var t1, t2 uint64
ret := C.tiledb_query_get_fragment_timestamp_range(
q.context.tiledbContext,
q.tiledbQuery,
(C.uint64_t)(num),
(*C.uint64_t)(unsafe.Pointer(&t1)),
(*C.uint64_t)(unsafe.Pointer(&t2)))
if ret != C.TILEDB_OK {
return nil, nil, fmt.Errorf("Error getting fragment timestamp: %s", q.context.LastError())
}
return &t1, &t2, nil
}
// Array returns array used by query.
func (q *Query) Array() (*Array, error) {
array := Array{context: q.context}
ret := C.tiledb_query_get_array(q.context.tiledbContext, q.tiledbQuery, &array.tiledbArray)
if ret != C.TILEDB_OK {
return nil, fmt.Errorf("Error getting array from query: %s", q.context.LastError())
}
freeOnGC(&array)
return &array, nil
}
// SetConfig sets the config of query.
func (q *Query) SetConfig(config *Config) error {
q.config = config
ret := C.tiledb_query_set_config(q.context.tiledbContext, q.tiledbQuery, q.config.tiledbConfig)
if ret != C.TILEDB_OK {
return fmt.Errorf("Error setting config on query: %s", q.context.LastError())
}
return nil
}
// Config gets the config of query.
func (q *Query) Config() (*Config, error) {
config := Config{}
ret := C.tiledb_query_get_config(q.context.tiledbContext, q.tiledbQuery, &config.tiledbConfig)
if ret != C.TILEDB_OK {
return nil, fmt.Errorf("Error getting config from query: %s", q.context.LastError())
}
freeOnGC(&config)
if q.config == nil {
q.config = &config
}
return &config, nil
}
// Stats gets stats for a query as json bytes.
func (q *Query) Stats() ([]byte, error) {
var stats *C.char
if ret := C.tiledb_query_get_stats(q.context.tiledbContext, q.tiledbQuery, &stats); ret != C.TILEDB_OK {
return nil, fmt.Errorf("Error getting stats from query: %s", q.context.LastError())
}
s := C.GoString(stats)
if ret := C.tiledb_stats_free_str(&stats); ret != C.TILEDB_OK {
return nil, fmt.Errorf("Error freeing string from dumping stats to string")
}
if s == "" {
return []byte("{}"), nil
}
return []byte(s), nil
}
// setResultBufferPointer sets the resultBufferElements for attribute
// pos = 0(offsets buffer) 1(data buffer) 2(validities buffer)
// The caller must hold the q.bufferMutex lock
func (q *Query) setResultBufferPointer(attribute string, pos int, ptr *uint64) {
ptrs, present := q.resultBufferElements[attribute]
if !present {
ptrs = [3]*uint64{nil, nil, nil}
}
ptrs[pos] = ptr
q.resultBufferElements[attribute] = ptrs
}
// SetDataBufferUnsafe sets the buffer for a fixed-sized attribute to a query.
// This takes an unsafe pointer which is passsed straight to tiledb c_api for advanced usage.
func (q *Query) SetDataBufferUnsafe(attribute string, buffer unsafe.Pointer, bufferSize uint64) (*uint64, error) {
q.bufferMutex.Lock()
defer q.bufferMutex.Unlock()
cAttribute := C.CString(attribute)
defer C.free(unsafe.Pointer(cAttribute))
ret := C.tiledb_query_set_data_buffer(
q.context.tiledbContext,
q.tiledbQuery,
cAttribute,
buffer,
(*C.uint64_t)(unsafe.Pointer(&bufferSize)))
if ret != C.TILEDB_OK {
return nil, fmt.Errorf("Error setting query data buffer: %s", q.context.LastError())
}
q.setResultBufferPointer(attribute, 1, &bufferSize)
return &bufferSize, nil
}
// SetDataBuffer sets the buffer for a fixed-sized attribute to a query.
func (q *Query) SetDataBuffer(attributeOrDimension string, buffer interface{}) (*uint64, error) {
bufferReflectType := reflect.TypeOf(buffer)
bufferReflectValue := reflect.ValueOf(buffer)
if bufferReflectValue.Kind() != reflect.Slice {
return nil, fmt.Errorf("Buffer passed must be a slice that is pre-allocated, type passed was: %s",
bufferReflectValue.Kind().String())
}
// Next get the attribute to validate the buffer type is the same as the attribute
schema, err := q.array.Schema()
if err != nil {
return nil, fmt.Errorf("Could not get array schema for SetDataBuffer: %s", err)
}
defer schema.Free()
domain, err := schema.Domain()
if err != nil {
return nil, fmt.Errorf("Could not get domain for SetDataBuffer: %s", attributeOrDimension)
}
defer domain.Free()
var attributeOrDimensionType Datatype
// If we are setting tiledb coordinates for a sparse array we want to check
// the domain type. The TILEDB_COORDS attribute is only materialized after
// the first write
if attributeOrDimension == TILEDB_COORDS {
attributeOrDimensionType, err = domain.Type()
if err != nil {
return nil, fmt.Errorf("Could not get domainType for SetDataBuffer: %s", attributeOrDimension)
}
} else {
hasDim, err := domain.HasDimension(attributeOrDimension)
if err != nil {
return nil, err
}
hasAttribute, err := schema.HasAttribute(attributeOrDimension)
if err != nil {
return nil, err
}
hasDimLabel, err := schema.HasDimensionLabel(attributeOrDimension)
if err != nil {
return nil, err
}
if hasDim {
dimension, err := domain.DimensionFromName(attributeOrDimension)
if err != nil {
return nil, fmt.Errorf("Could not get attribute or dimension for SetDataBuffer: %s",
attributeOrDimension)
}
defer dimension.Free()
attributeOrDimensionType, err = dimension.Type()
if err != nil {
return nil, fmt.Errorf("Could not get dimensionType for SetDataBuffer: %s",
attributeOrDimension)
}
} else if hasAttribute {
schemaAttribute, err := schema.AttributeFromName(attributeOrDimension)
if err != nil {
return nil, fmt.Errorf("Could not get attribute %s for SetDataBuffer",
attributeOrDimension)
}
defer schemaAttribute.Free()
attributeOrDimensionType, err = schemaAttribute.Type()
if err != nil {
return nil, fmt.Errorf("Could not get attributeType for SetDataBuffer: %s",
attributeOrDimension)
}
} else if hasDimLabel {
attributeOrDimensionType, err = q.getDimensionLabelDataType(attributeOrDimension)
if err != nil {
return nil, fmt.Errorf("Could not get dimension label type for SetDataBuffer: %s",
attributeOrDimension)
}
} else {
return nil, fmt.Errorf("Error in SetDataBuffer for %s: "+
"Attribute/dimension/label does not exist.", attributeOrDimension)
}
}
bufferType := bufferReflectType.Elem().Kind()
if attributeOrDimensionType.ReflectKind() != bufferType {
return nil, fmt.Errorf("Buffer and Attribute do not have the same data types. Buffer: %s, Attribute: %s",
bufferType.String(),
attributeOrDimensionType.ReflectKind().String())
}
var cbuffer unsafe.Pointer
// Get length of slice, this will be multiplied by size of datatype below
bufferSize := uint64(bufferReflectValue.Len())
if bufferSize == uint64(0) {
return nil, errors.New("Buffer has no length, vbuffers are required to be initialized before reading or writting")
}
// Acquire a lock to make appending to buffer slice thread safe
q.bufferMutex.Lock()
defer q.bufferMutex.Unlock()
switch bufferType {
case reflect.Int:
// Set buffersize
bufferSize = bufferSize * bytesizes.Int
// Create buffer void*
tmpBuffer := buffer.([]int)
// Store slice so underlying array is not gc'ed
q.buffers = append(q.buffers, tmpBuffer)
cbuffer = unsafe.Pointer(&(tmpBuffer)[0])
case reflect.Int8:
// Set buffersize
bufferSize = bufferSize * bytesizes.Int8
// Create buffer void*
tmpBuffer := buffer.([]int8)
// Store slice so underlying array is not gc'ed
q.buffers = append(q.buffers, tmpBuffer)
cbuffer = unsafe.Pointer(&(tmpBuffer)[0])
case reflect.Int16:
// Set buffersize
bufferSize = bufferSize * bytesizes.Int16
// Create buffer void*
tmpBuffer := buffer.([]int16)
// Store slice so underlying array is not gc'ed
q.buffers = append(q.buffers, tmpBuffer)
cbuffer = unsafe.Pointer(&(tmpBuffer)[0])
case reflect.Int32:
// Set buffersize
bufferSize = bufferSize * bytesizes.Int32
// Create buffer void*
tmpBuffer := buffer.([]int32)
// Store slice so underlying array is not gc'ed
q.buffers = append(q.buffers, tmpBuffer)
cbuffer = unsafe.Pointer(&(tmpBuffer)[0])
case reflect.Int64:
// Set buffersize
bufferSize = bufferSize * bytesizes.Int64
// Create buffer void*
tmpBuffer := buffer.([]int64)
// Store slice so underlying array is not gc'ed
q.buffers = append(q.buffers, tmpBuffer)
cbuffer = unsafe.Pointer(&(tmpBuffer)[0])
case reflect.Uint:
// Set buffersize
bufferSize = bufferSize * bytesizes.Uint
// Create buffer void*
tmpBuffer := buffer.([]uint)
// Store slice so underlying array is not gc'ed
q.buffers = append(q.buffers, tmpBuffer)
cbuffer = unsafe.Pointer(&(tmpBuffer)[0])
case reflect.Uint8:
// Set buffersize
bufferSize = bufferSize * bytesizes.Uint8
// Create buffer void*
tmpBuffer := buffer.([]uint8)
// Store slice so underlying array is not gc'ed
q.buffers = append(q.buffers, tmpBuffer)
cbuffer = unsafe.Pointer(&(tmpBuffer)[0])
case reflect.Uint16:
// Set buffersize
bufferSize = bufferSize * bytesizes.Uint16
// Create buffer void*
tmpBuffer := buffer.([]uint16)
// Store slice so underlying array is not gc'ed
q.buffers = append(q.buffers, tmpBuffer)
cbuffer = unsafe.Pointer(&(tmpBuffer)[0])
case reflect.Uint32:
// Set buffersize
bufferSize = bufferSize * bytesizes.Uint32
// Create buffer void*
tmpBuffer := buffer.([]uint32)
// Store slice so underlying array is not gc'ed
q.buffers = append(q.buffers, tmpBuffer)
cbuffer = unsafe.Pointer(&(tmpBuffer)[0])
case reflect.Uint64:
// Set buffersize
bufferSize = bufferSize * bytesizes.Uint64
// Create buffer void*
tmpBuffer := buffer.([]uint64)
// Store slice so underlying array is not gc'ed
q.buffers = append(q.buffers, tmpBuffer)
cbuffer = unsafe.Pointer(&(tmpBuffer)[0])
case reflect.Float32:
// Set buffersize
bufferSize = bufferSize * bytesizes.Float32
// Create buffer void*
tmpBuffer := buffer.([]float32)
// Store slice so underlying array is not gc'ed
q.buffers = append(q.buffers, tmpBuffer)
cbuffer = unsafe.Pointer(&(tmpBuffer)[0])
case reflect.Float64:
// Set buffersize
bufferSize = bufferSize * bytesizes.Float64
// Create buffer void*
tmpBuffer := buffer.([]float64)
// Store slice so underlying array is not gc'ed
q.buffers = append(q.buffers, tmpBuffer)
cbuffer = unsafe.Pointer(&(tmpBuffer)[0])
case reflect.Bool:
// Set buffersize
bufferSize = bufferSize * bytesizes.Bool
// Create buffer void*
tmpBuffer := buffer.([]bool)
// Store slice so underlying array is not gc'ed
q.buffers = append(q.buffers, tmpBuffer)
cbuffer = unsafe.Pointer(&(tmpBuffer)[0])
default:
return nil,
fmt.Errorf("Unrecognized buffer type passed: %s",
bufferType.String())
}
cAttributeOrDimension := C.CString(attributeOrDimension)
defer C.free(unsafe.Pointer(cAttributeOrDimension))
ret := C.tiledb_query_set_data_buffer(
q.context.tiledbContext,
q.tiledbQuery,
cAttributeOrDimension,
cbuffer,
(*C.uint64_t)(unsafe.Pointer(&bufferSize)))
if ret != C.TILEDB_OK {
return nil, fmt.Errorf("Error setting query data buffer: %s", q.context.LastError())
}
q.setResultBufferPointer(attributeOrDimension, 1, &bufferSize)
return &bufferSize, nil
}
// GetDataBuffer retrieves the data buffer of an attribute/dimension.
func (q *Query) GetDataBuffer(attributeOrDimension string) (interface{}, error) {