-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathzarr_metadata.cpp
More file actions
2397 lines (2261 loc) · 94.1 KB
/
zarr_metadata.cpp
File metadata and controls
2397 lines (2261 loc) · 94.1 KB
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
#include "zarr_metadata.hpp"
#include "duckdb/common/helper.hpp"
#include "duckdb/common/file_system.hpp"
#include "duckdb/common/string_util.hpp"
#include "duckdb/common/types/value.hpp"
#include "duckdb/function/table_function.hpp"
#include "duckdb/main/extension_helper.hpp"
#include "duckdb/planner/filter/conjunction_filter.hpp"
#include "duckdb/planner/filter/constant_filter.hpp"
#include "duckdb/planner/filter/in_filter.hpp"
#include "duckdb/planner/filter/null_filter.hpp"
#include "miniz_wrapper.hpp"
#include "yyjson.hpp"
#include "zstd.h"
#include <algorithm>
#include <cstring>
#include <limits>
#include <tuple>
namespace duckdb {
using namespace duckdb_yyjson; // NOLINT
struct ZarrGroupEntry {
string store_path;
string group_path;
int64_t zarr_format;
string metadata_path;
};
struct ZarrArrayEntry {
ZarrArrayEntry() {
}
ZarrArrayEntry(string store_path_p, string array_path_p, int64_t zarr_format_p, int64_t rank_p,
vector<int64_t> shape_p, vector<int64_t> chunks_p, string dtype_p, string order_p,
string compressor_p, string fill_value_p, string chunk_key_encoding_p, string dimension_separator_p,
string metadata_path_p, bool supports_cells_p, string cells_error_p, bool is_sharding_indexed_p,
vector<int64_t> storage_chunks_p, vector<int64_t> inner_chunks_p, string inner_compressor_p,
string index_codecs_p, string index_location_p)
: store_path(std::move(store_path_p)), array_path(std::move(array_path_p)), zarr_format(zarr_format_p),
rank(rank_p), shape(std::move(shape_p)), chunks(std::move(chunks_p)), dtype(std::move(dtype_p)),
order(std::move(order_p)), compressor(std::move(compressor_p)), fill_value(std::move(fill_value_p)),
chunk_key_encoding(std::move(chunk_key_encoding_p)), dimension_separator(std::move(dimension_separator_p)),
metadata_path(std::move(metadata_path_p)), supports_cells(supports_cells_p),
cells_error(std::move(cells_error_p)), is_sharding_indexed(is_sharding_indexed_p),
storage_chunks(std::move(storage_chunks_p)), inner_chunks(std::move(inner_chunks_p)),
inner_compressor(std::move(inner_compressor_p)), index_codecs(std::move(index_codecs_p)),
index_location(std::move(index_location_p)) {
}
string store_path;
string array_path;
int64_t zarr_format;
int64_t rank;
vector<int64_t> shape;
vector<int64_t> chunks;
string dtype;
string order;
string compressor;
string fill_value;
string chunk_key_encoding;
string dimension_separator;
string metadata_path;
bool supports_cells;
string cells_error;
bool is_sharding_indexed = false;
vector<int64_t> storage_chunks;
vector<int64_t> inner_chunks;
string inner_compressor;
string index_codecs;
string index_location;
};
struct ZarrChunkEntry {
ZarrChunkEntry() {
}
ZarrChunkEntry(string store_path_p, string array_path_p, string chunk_key_p, vector<int64_t> chunk_coords_p,
string file_path_p, int64_t file_size_bytes_p, bool present_p, bool is_virtual_inner_chunk_p,
vector<int64_t> storage_chunk_coords_p, vector<int64_t> inner_chunk_coords_p)
: store_path(std::move(store_path_p)), array_path(std::move(array_path_p)), chunk_key(std::move(chunk_key_p)),
chunk_coords(std::move(chunk_coords_p)), file_path(std::move(file_path_p)),
file_size_bytes(file_size_bytes_p), present(present_p), is_virtual_inner_chunk(is_virtual_inner_chunk_p),
storage_chunk_coords(std::move(storage_chunk_coords_p)), inner_chunk_coords(std::move(inner_chunk_coords_p)) {
}
string store_path;
string array_path;
string chunk_key;
vector<int64_t> chunk_coords;
string file_path;
int64_t file_size_bytes;
bool present;
bool is_virtual_inner_chunk = false;
vector<int64_t> storage_chunk_coords;
vector<int64_t> inner_chunk_coords;
};
struct ZarrNumericType {
LogicalType logical_type;
idx_t element_size;
bool is_float;
bool is_signed;
bool is_unsigned;
bool is_boolean;
bool little_endian;
};
template <class ENTRY>
struct ZarrBindData : public TableFunctionData {
explicit ZarrBindData(vector<ENTRY> entries_p) : entries(std::move(entries_p)) {
}
vector<ENTRY> entries;
};
struct ZarrGlobalState : public GlobalTableFunctionState {
idx_t offset = 0;
};
struct ZarrCellsBindData : public TableFunctionData {
ZarrCellsBindData(ZarrArrayEntry array_p, vector<ZarrChunkEntry> chunks_p)
: array(std::move(array_p)), chunks(std::move(chunks_p)) {
}
ZarrArrayEntry array;
vector<ZarrChunkEntry> chunks;
};
struct ZarrCellsGlobalState : public GlobalTableFunctionState {
vector<column_t> column_ids;
vector<idx_t> projection_ids;
unique_ptr<TableFilterSet> filters;
vector<idx_t> chunk_indexes;
ZarrNumericType dtype;
Value fill_value;
bool has_fill_value = false;
idx_t chunk_element_count = 0;
idx_t expected_chunk_bytes = 0;
idx_t next_chunk_offset = 0;
idx_t current_chunk_index = DConstants::INVALID_INDEX;
idx_t current_linear_index = 0;
vector<char> decoded_chunk;
};
enum class ZarrVersionOverride : uint8_t { AUTO, V2, V3 };
static ZarrGroupEntry ParseGroupMetadata(yyjson_val *root, const string &store_path, const string &relative_path,
const string &metadata_path);
static ZarrGroupEntry ParseGroupMetadataV3(yyjson_val *root, const string &store_path, const string &relative_path,
const string &metadata_path);
static ZarrArrayEntry ParseArrayMetadataObject(yyjson_val *root, const string &store_path, const string &relative_path,
const string &metadata_path);
static ZarrArrayEntry ParseArrayMetadataObjectV3(yyjson_val *root, const string &store_path,
const string &relative_path, const string &metadata_path);
static vector<ZarrChunkEntry> GenerateChunkEntries(FileSystem &fs, const string &store_path,
const ZarrArrayEntry &array, bool include_missing);
static idx_t FlattenCoordsCOrder(const vector<int64_t> &coords, const vector<int64_t> &shape);
static vector<int64_t> ShardInnerChunksPerShard(const ZarrArrayEntry &array);
static string RequireNodeType(yyjson_val *root, const string &metadata_path);
static ZarrArrayEntry MakeArrayEntry(string store_path, string array_path, int64_t zarr_format, int64_t rank,
vector<int64_t> shape, vector<int64_t> chunks, string dtype, string order,
string compressor, string fill_value, string chunk_key_encoding,
string dimension_separator, string metadata_path, bool supports_cells,
string cells_error, bool is_sharding_indexed, vector<int64_t> storage_chunks,
vector<int64_t> inner_chunks, string inner_compressor, string index_codecs,
string index_location) {
ZarrArrayEntry entry;
entry.store_path = std::move(store_path);
entry.array_path = std::move(array_path);
entry.zarr_format = zarr_format;
entry.shape = std::move(shape);
entry.chunks = std::move(chunks);
entry.rank = NumericCast<int64_t>(entry.shape.size());
D_ASSERT(rank == entry.rank);
entry.dtype = std::move(dtype);
entry.order = std::move(order);
entry.compressor = std::move(compressor);
entry.fill_value = std::move(fill_value);
entry.chunk_key_encoding = std::move(chunk_key_encoding);
entry.dimension_separator = std::move(dimension_separator);
entry.metadata_path = std::move(metadata_path);
entry.supports_cells = supports_cells;
entry.cells_error = std::move(cells_error);
entry.is_sharding_indexed = is_sharding_indexed;
entry.storage_chunks = std::move(storage_chunks);
entry.inner_chunks = std::move(inner_chunks);
entry.inner_compressor = std::move(inner_compressor);
entry.index_codecs = std::move(index_codecs);
entry.index_location = std::move(index_location);
return entry;
}
static string JoinNodePath(const string &base, const string &name) {
if (base.empty()) {
return name;
}
return base + "/" + name;
}
static string FormatGroupPath(const string &relative_path) {
return relative_path.empty() ? "/" : relative_path;
}
static string ReadTextFile(FileSystem &fs, const string &path) {
auto handle = fs.OpenFile(path, FileFlags::FILE_FLAGS_READ);
auto size = handle->GetFileSize();
if (size == 0) {
return "";
}
auto buffer = make_unsafe_uniq_array<char>(size);
fs.Read(*handle, buffer.get(), NumericCast<int64_t>(size));
return string(buffer.get(), size);
}
static vector<char> ReadBinaryFile(FileSystem &fs, const string &path) {
auto handle = fs.OpenFile(path, FileFlags::FILE_FLAGS_READ);
auto size = handle->GetFileSize();
vector<char> buffer(size);
if (size > 0) {
fs.Read(*handle, buffer.data(), NumericCast<int64_t>(size));
}
return buffer;
}
static yyjson_val *RequireObjectKey(yyjson_val *obj, const char *key) {
auto value = yyjson_obj_get(obj, key);
if (!value) {
throw InvalidInputException("Required Zarr metadata key \"%s\" was not found", key);
}
return value;
}
static int64_t RequireInt64(yyjson_val *obj, const char *key) {
auto value = RequireObjectKey(obj, key);
if (yyjson_is_uint(value)) {
return NumericCast<int64_t>(unsafe_yyjson_get_uint(value));
}
if (yyjson_is_sint(value)) {
return unsafe_yyjson_get_sint(value);
}
throw InvalidInputException("Zarr metadata key \"%s\" is not an integer", key);
}
static string OptionalString(yyjson_val *obj, const char *key, const string &default_value = "") {
auto value = yyjson_obj_get(obj, key);
if (!value || yyjson_is_null(value)) {
return default_value;
}
if (!yyjson_is_str(value)) {
throw InvalidInputException("Zarr metadata key \"%s\" is not a string", key);
}
return string(unsafe_yyjson_get_str(value), unsafe_yyjson_get_len(value));
}
static vector<int64_t> RequireInt64Array(yyjson_val *obj, const char *key) {
auto value = RequireObjectKey(obj, key);
if (!yyjson_is_arr(value)) {
throw InvalidInputException("Zarr metadata key \"%s\" is not an array", key);
}
vector<int64_t> result;
result.reserve(unsafe_yyjson_get_len(value));
yyjson_val *element;
yyjson_arr_iter iter = yyjson_arr_iter_with(value);
while ((element = yyjson_arr_iter_next(&iter))) {
if (yyjson_is_uint(element)) {
result.push_back(NumericCast<int64_t>(unsafe_yyjson_get_uint(element)));
} else if (yyjson_is_sint(element)) {
result.push_back(unsafe_yyjson_get_sint(element));
} else {
throw InvalidInputException("Zarr metadata key \"%s\" contains a non-integer array element", key);
}
}
return result;
}
static yyjson_val *RequireObject(yyjson_val *obj, const char *key) {
auto value = RequireObjectKey(obj, key);
if (!yyjson_is_obj(value)) {
throw InvalidInputException("Zarr metadata key \"%s\" is not an object", key);
}
return value;
}
static yyjson_val *RequireArray(yyjson_val *obj, const char *key) {
auto value = RequireObjectKey(obj, key);
if (!yyjson_is_arr(value)) {
throw InvalidInputException("Zarr metadata key \"%s\" is not an array", key);
}
return value;
}
static string JsonToString(yyjson_val *value) {
if (!value || yyjson_is_null(value)) {
return "";
}
size_t len = 0;
auto rendered = yyjson_val_write(value, YYJSON_WRITE_NOFLAG, &len);
if (!rendered) {
throw InvalidInputException("Failed to render JSON metadata");
}
string result(rendered, len);
free(rendered);
return result;
}
static string NormalizeArrayPath(const string &path) {
idx_t start = 0;
idx_t end = path.size();
while (start < end && path[start] == '/') {
start++;
}
while (end > start && path[end - 1] == '/') {
end--;
}
return path.substr(start, end - start);
}
static string NormalizeStorePath(FileSystem &fs, const string &path) {
if (FileSystem::IsRemoteFile(path)) {
return path;
}
return fs.ExpandPath(path);
}
static ZarrVersionOverride ParseZarrVersionOverride(const Value &value, const string &function_name) {
if (value.IsNull()) {
return ZarrVersionOverride::AUTO;
}
auto text = StringUtil::Lower(StringValue::Get(value));
if (text.empty() || text == "auto") {
return ZarrVersionOverride::AUTO;
}
if (text == "2" || text == "v2") {
return ZarrVersionOverride::V2;
}
if (text == "3" || text == "v3") {
return ZarrVersionOverride::V3;
}
throw BinderException("%s version override must be one of auto, v2, or v3", function_name);
}
static idx_t Product(const vector<int64_t> &values) {
idx_t result = 1;
for (auto value : values) {
if (value < 0) {
throw InvalidInputException("Negative Zarr dimensions are not supported");
}
auto cast_value = NumericCast<idx_t>(value);
if (cast_value != 0 && result > std::numeric_limits<idx_t>::max() / cast_value) {
throw InvalidInputException("Zarr dimension product overflow");
}
result *= cast_value;
}
return result;
}
static string ParseCompressorId(const string &compressor) {
if (compressor.empty()) {
return "";
}
unique_ptr<yyjson_doc, decltype(&yyjson_doc_free)> doc(yyjson_read(compressor.c_str(), compressor.size(), 0),
yyjson_doc_free);
if (!doc) {
throw InvalidInputException("Failed to parse Zarr compressor metadata");
}
auto root = yyjson_doc_get_root(doc.get());
if (!yyjson_is_obj(root)) {
throw InvalidInputException("Zarr compressor metadata is not an object");
}
return OptionalString(root, "id", OptionalString(root, "name"));
}
static bool HostIsLittleEndian() {
uint16_t value = 1;
return *reinterpret_cast<unsigned char *>(&value) == 1;
}
static ZarrNumericType ParseNumericDType(const string &dtype) {
if (dtype.size() < 3) {
throw InvalidInputException("Unsupported Zarr dtype: %s", dtype);
}
ZarrNumericType result;
auto endian = dtype[0];
auto kind = dtype[1];
int64_t width;
try {
width = std::stoll(dtype.substr(2));
} catch (const std::exception &) {
throw InvalidInputException("Unsupported Zarr dtype: %s", dtype);
}
if (width <= 0) {
throw InvalidInputException("Unsupported Zarr dtype: %s", dtype);
}
result.element_size = NumericCast<idx_t>(width);
result.is_float = false;
result.is_signed = false;
result.is_unsigned = false;
result.is_boolean = false;
switch (endian) {
case '<':
result.little_endian = true;
break;
case '>':
result.little_endian = false;
break;
case '=':
result.little_endian = HostIsLittleEndian();
break;
case '|':
if (width != 1) {
throw InvalidInputException("Endian-agnostic dtype is only supported for single-byte values: %s", dtype);
}
result.little_endian = HostIsLittleEndian();
break;
default:
throw InvalidInputException("Unsupported Zarr dtype byte order marker in dtype: %s", dtype);
}
if (kind == 'i') {
result.is_signed = true;
switch (width) {
case 1:
result.logical_type = LogicalType::TINYINT;
break;
case 2:
result.logical_type = LogicalType::SMALLINT;
break;
case 4:
result.logical_type = LogicalType::INTEGER;
break;
case 8:
result.logical_type = LogicalType::BIGINT;
break;
default:
throw InvalidInputException("Unsupported signed integer dtype: %s", dtype);
}
return result;
}
if (kind == 'u') {
result.is_unsigned = true;
switch (width) {
case 1:
result.logical_type = LogicalType::UTINYINT;
break;
case 2:
result.logical_type = LogicalType::USMALLINT;
break;
case 4:
result.logical_type = LogicalType::UINTEGER;
break;
case 8:
result.logical_type = LogicalType::UBIGINT;
break;
default:
throw InvalidInputException("Unsupported unsigned integer dtype: %s", dtype);
}
return result;
}
if (kind == 'b') {
result.is_boolean = true;
if (width != 1) {
throw InvalidInputException("Unsupported boolean dtype: %s", dtype);
}
result.logical_type = LogicalType::BOOLEAN;
return result;
}
if (kind == 'f') {
result.is_float = true;
switch (width) {
case 2:
result.logical_type = LogicalType::FLOAT;
break;
case 4:
result.logical_type = LogicalType::FLOAT;
break;
case 8:
result.logical_type = LogicalType::DOUBLE;
break;
default:
throw InvalidInputException("Unsupported floating-point dtype: %s", dtype);
}
return result;
}
throw InvalidInputException("Unsupported Zarr dtype: %s", dtype);
}
static string GetExtensionName(yyjson_val *extension, const string &metadata_path, const string &field_name) {
if (yyjson_is_str(extension)) {
return string(unsafe_yyjson_get_str(extension), unsafe_yyjson_get_len(extension));
}
if (yyjson_is_obj(extension)) {
auto name = OptionalString(extension, "name");
if (name.empty()) {
throw InvalidInputException("%s contains an extension without a name in %s", field_name, metadata_path);
}
return name;
}
throw InvalidInputException("%s contains an invalid extension value in %s", field_name, metadata_path);
}
static yyjson_val *GetExtensionConfiguration(yyjson_val *extension, const string &metadata_path,
const string &field_name) {
if (!yyjson_is_obj(extension)) {
return nullptr;
}
auto configuration = yyjson_obj_get(extension, "configuration");
if (!configuration) {
return nullptr;
}
if (!yyjson_is_obj(configuration)) {
throw InvalidInputException("%s configuration is not an object in %s", field_name, metadata_path);
}
return configuration;
}
static string ParseV3DataType(yyjson_val *root, const string &metadata_path, bool little_endian) {
auto data_type = RequireObjectKey(root, "data_type");
if (!yyjson_is_str(data_type)) {
throw InvalidInputException("Only string Zarr v3 data_type values are currently supported: %s", metadata_path);
}
string type_name(unsafe_yyjson_get_str(data_type), unsafe_yyjson_get_len(data_type));
if (type_name == "bool") {
return "|b1";
}
if (type_name == "int8") {
return "|i1";
}
if (type_name == "uint8") {
return "|u1";
}
string endian_prefix = little_endian ? "<" : ">";
if (type_name == "int16") {
return endian_prefix + "i2";
}
if (type_name == "int32") {
return endian_prefix + "i4";
}
if (type_name == "int64") {
return endian_prefix + "i8";
}
if (type_name == "uint16") {
return endian_prefix + "u2";
}
if (type_name == "uint32") {
return endian_prefix + "u4";
}
if (type_name == "uint64") {
return endian_prefix + "u8";
}
if (type_name == "float16") {
return endian_prefix + "f2";
}
if (type_name == "float32") {
return endian_prefix + "f4";
}
if (type_name == "float64") {
return endian_prefix + "f8";
}
throw InvalidInputException("Unsupported Zarr v3 data_type in %s: %s", metadata_path, type_name);
}
static bool IsIdentityPermutation(const vector<int64_t> &order) {
for (idx_t i = 0; i < order.size(); i++) {
if (order[i] != NumericCast<int64_t>(i)) {
return false;
}
}
return true;
}
static bool IsReversePermutation(const vector<int64_t> &order) {
for (idx_t i = 0; i < order.size(); i++) {
auto expected = NumericCast<int64_t>(order.size() - i - 1);
if (order[i] != expected) {
return false;
}
}
return true;
}
static string JsonObjectWithId(yyjson_val *codec_value, const string &codec_name) {
auto object = JsonToString(codec_value);
if (!object.empty()) {
return object;
}
return "{\"id\":\"" + codec_name + "\"}";
}
static bool IsSupportedBloscShuffle(const string &shuffle, idx_t typesize) {
if (shuffle.empty() || shuffle == "noshuffle") {
return true;
}
if (shuffle == "shuffle") {
return true;
}
if (shuffle == "bitshuffle") {
return typesize == 1;
}
return false;
}
static float DecodeFloat16(uint16_t half_bits) {
auto sign = (half_bits >> 15) & 0x1;
auto exponent = (half_bits >> 10) & 0x1f;
auto mantissa = half_bits & 0x3ff;
uint32_t float_bits;
if (exponent == 0) {
if (mantissa == 0) {
float_bits = NumericCast<uint32_t>(sign) << 31;
} else {
exponent = 1;
while ((mantissa & 0x400) == 0) {
mantissa <<= 1;
exponent--;
}
mantissa &= 0x3ff;
auto float_exponent = NumericCast<uint32_t>(exponent + (127 - 15));
float_bits =
(NumericCast<uint32_t>(sign) << 31) | (float_exponent << 23) | (NumericCast<uint32_t>(mantissa) << 13);
}
} else if (exponent == 0x1f) {
float_bits = (NumericCast<uint32_t>(sign) << 31) | 0x7f800000U | (NumericCast<uint32_t>(mantissa) << 13);
} else {
auto float_exponent = NumericCast<uint32_t>(exponent + (127 - 15));
float_bits =
(NumericCast<uint32_t>(sign) << 31) | (float_exponent << 23) | (NumericCast<uint32_t>(mantissa) << 13);
}
float value;
std::memcpy(&value, &float_bits, sizeof(value));
return value;
}
static uint64_t ReadUnsignedInteger(const char *ptr, idx_t bytes, bool little_endian) {
uint64_t result = 0;
if (little_endian) {
for (idx_t i = 0; i < bytes; i++) {
result |= static_cast<uint64_t>(static_cast<unsigned char>(ptr[i])) << (8 * i);
}
} else {
for (idx_t i = 0; i < bytes; i++) {
result = (result << 8) | static_cast<uint64_t>(static_cast<unsigned char>(ptr[i]));
}
}
return result;
}
static int64_t ReadSignedInteger(const char *ptr, idx_t bytes, bool little_endian) {
auto unsigned_value = ReadUnsignedInteger(ptr, bytes, little_endian);
if (bytes == sizeof(int64_t)) {
return static_cast<int64_t>(unsigned_value);
}
auto bit_width = bytes * 8;
auto sign_bit = uint64_t(1) << (bit_width - 1);
if (unsigned_value & sign_bit) {
auto mask = ~((uint64_t(1) << bit_width) - 1);
unsigned_value |= mask;
}
return static_cast<int64_t>(unsigned_value);
}
static Value DecodeNumericValue(const char *ptr, const ZarrNumericType &dtype) {
if (dtype.is_boolean) {
return Value::BOOLEAN(static_cast<unsigned char>(ptr[0]) != 0);
}
if (dtype.is_float) {
if (dtype.element_size == 2) {
auto bits = NumericCast<uint16_t>(ReadUnsignedInteger(ptr, dtype.element_size, dtype.little_endian));
return Value::FLOAT(DecodeFloat16(bits));
}
if (dtype.element_size == sizeof(float)) {
auto bits = NumericCast<uint32_t>(ReadUnsignedInteger(ptr, dtype.element_size, dtype.little_endian));
float value;
std::memcpy(&value, &bits, sizeof(value));
return Value::FLOAT(value);
}
if (dtype.element_size == sizeof(double)) {
auto bits = ReadUnsignedInteger(ptr, dtype.element_size, dtype.little_endian);
double value;
std::memcpy(&value, &bits, sizeof(value));
return Value::DOUBLE(value);
}
}
if (dtype.is_signed) {
auto value = ReadSignedInteger(ptr, dtype.element_size, dtype.little_endian);
switch (dtype.element_size) {
case 1:
return Value::TINYINT(NumericCast<int8_t>(value));
case 2:
return Value::SMALLINT(NumericCast<int16_t>(value));
case 4:
return Value::INTEGER(NumericCast<int32_t>(value));
case 8:
return Value::BIGINT(value);
default:
break;
}
}
if (dtype.is_unsigned) {
auto value = ReadUnsignedInteger(ptr, dtype.element_size, dtype.little_endian);
switch (dtype.element_size) {
case 1:
return Value::UTINYINT(NumericCast<uint8_t>(value));
case 2:
return Value::USMALLINT(NumericCast<uint16_t>(value));
case 4:
return Value::UINTEGER(NumericCast<uint32_t>(value));
case 8:
return Value::UBIGINT(value);
default:
break;
}
}
throw InvalidInputException("Failed to decode Zarr numeric dtype");
}
static vector<int64_t> LinearToCoords(idx_t linear_index, const vector<int64_t> &shape, const string &order) {
vector<int64_t> coordinates(shape.size(), 0);
if (shape.empty()) {
return coordinates;
}
if (order == "F") {
for (idx_t i = 0; i < shape.size(); i++) {
auto dim = NumericCast<idx_t>(shape[i]);
coordinates[i] = NumericCast<int64_t>(linear_index % dim);
linear_index /= dim;
}
return coordinates;
}
for (idx_t offset = 0; offset < shape.size(); offset++) {
auto index = shape.size() - offset - 1;
auto dim = NumericCast<idx_t>(shape[index]);
coordinates[index] = NumericCast<int64_t>(linear_index % dim);
linear_index /= dim;
}
return coordinates;
}
static void ByteUnshuffle(const char *input, idx_t input_size, idx_t typesize, vector<char> &output) {
if (typesize <= 1) {
output.assign(input, input + input_size);
return;
}
auto element_count = input_size / typesize;
output.resize(input_size);
for (idx_t element_idx = 0; element_idx < element_count; element_idx++) {
for (idx_t byte_idx = 0; byte_idx < typesize; byte_idx++) {
output[element_idx * typesize + byte_idx] = input[byte_idx * element_count + element_idx];
}
}
}
static void BitUnshuffleTypesizeOne(const char *input, idx_t input_size, vector<char> &output) {
if (input_size % 8 != 0) {
throw InvalidInputException("Unsupported Blosc bitshuffle payload size: %llu", input_size);
}
auto plane_size = input_size / 8;
output.assign(input_size, 0);
for (idx_t i = 0; i < input_size; i++) {
auto byte_index = i / 8;
auto bit_index = i % 8;
uint8_t value = 0;
for (idx_t bit = 0; bit < 8; bit++) {
auto bit_value = (static_cast<uint8_t>(input[bit * plane_size + byte_index]) >> bit_index) & 0x1;
value |= NumericCast<uint8_t>(bit_value << bit);
}
output[i] = NumericCast<char>(value);
}
}
static vector<char> DecompressZstd(const char *compressed_data, idx_t compressed_size, idx_t expected_size) {
vector<char> result(expected_size);
auto decompressed_size =
duckdb_zstd::ZSTD_decompress(result.data(), result.size(), compressed_data, compressed_size);
if (duckdb_zstd::ZSTD_isError(decompressed_size)) {
throw InvalidInputException("Failed to decompress Zstd payload inside Blosc chunk");
}
if (decompressed_size != expected_size) {
throw InvalidInputException("Unexpected Zstd decompressed size: expected %llu bytes, got %llu bytes",
expected_size, decompressed_size);
}
return result;
}
static vector<char> DecompressBloscChunk(const vector<char> &compressed_data, const string &compressor,
idx_t expected_size) {
if (compressed_data.size() < 20) {
throw InvalidInputException("Blosc chunk is too small");
}
unique_ptr<yyjson_doc, decltype(&yyjson_doc_free)> doc(yyjson_read(compressor.c_str(), compressor.size(), 0),
yyjson_doc_free);
if (!doc) {
throw InvalidInputException("Failed to parse Blosc codec metadata");
}
auto root = yyjson_doc_get_root(doc.get());
auto configuration = yyjson_obj_get(root, "configuration");
if (configuration) {
if (!yyjson_is_obj(configuration)) {
throw InvalidInputException("Blosc codec configuration is not an object");
}
root = configuration;
}
auto cname = OptionalString(root, "cname");
auto shuffle = OptionalString(root, "shuffle", "noshuffle");
auto typesize_value = yyjson_obj_get(root, "typesize");
if (!typesize_value || (!yyjson_is_uint(typesize_value) && !yyjson_is_sint(typesize_value))) {
throw InvalidInputException("Blosc codec metadata is missing integer typesize");
}
auto typesize = yyjson_is_uint(typesize_value) ? NumericCast<idx_t>(unsafe_yyjson_get_uint(typesize_value))
: NumericCast<idx_t>(unsafe_yyjson_get_sint(typesize_value));
if (cname != "zstd") {
throw InvalidInputException("Only Blosc with cname=zstd is currently supported");
}
auto nbytes = NumericCast<idx_t>(Load<uint32_t>(reinterpret_cast<const_data_ptr_t>(compressed_data.data() + 4)));
auto blocksize = NumericCast<idx_t>(Load<uint32_t>(reinterpret_cast<const_data_ptr_t>(compressed_data.data() + 8)));
auto cbytes = NumericCast<idx_t>(Load<uint32_t>(reinterpret_cast<const_data_ptr_t>(compressed_data.data() + 12)));
if (nbytes != expected_size) {
throw InvalidInputException("Blosc chunk size mismatch: expected %llu bytes, got %llu bytes", expected_size,
nbytes);
}
if (cbytes != compressed_data.size()) {
throw InvalidInputException("Unexpected Blosc compressed byte count");
}
auto nblocks = (nbytes + blocksize - 1) / blocksize;
auto offsets_table_size = nblocks * sizeof(uint32_t);
if (compressed_data.size() < 16 + offsets_table_size) {
throw InvalidInputException("Blosc chunk is missing the block offsets table");
}
vector<char> result;
result.reserve(expected_size);
for (idx_t block_idx = 0; block_idx < nblocks; block_idx++) {
auto block_offset_ptr = compressed_data.data() + 16 + block_idx * sizeof(uint32_t);
auto block_offset = NumericCast<idx_t>(Load<uint32_t>(reinterpret_cast<const_data_ptr_t>(block_offset_ptr)));
if (block_offset + sizeof(uint32_t) > compressed_data.size()) {
throw InvalidInputException("Invalid Blosc block offset");
}
auto block_cbytes = NumericCast<idx_t>(
Load<uint32_t>(reinterpret_cast<const_data_ptr_t>(compressed_data.data() + block_offset)));
auto block_payload_offset = block_offset + sizeof(uint32_t);
if (block_payload_offset + block_cbytes > compressed_data.size()) {
throw InvalidInputException("Invalid Blosc block payload length");
}
auto block_expected_size = MinValue<idx_t>(blocksize, nbytes - block_idx * blocksize);
auto raw_block =
DecompressZstd(compressed_data.data() + block_payload_offset, block_cbytes, block_expected_size);
vector<char> decoded_block;
if (shuffle == "shuffle") {
ByteUnshuffle(raw_block.data(), raw_block.size(), typesize, decoded_block);
} else if (shuffle == "bitshuffle") {
if (typesize != 1) {
throw InvalidInputException("Blosc bitshuffle is currently only supported for typesize=1");
}
BitUnshuffleTypesizeOne(raw_block.data(), raw_block.size(), decoded_block);
} else {
decoded_block = std::move(raw_block);
}
result.insert(result.end(), decoded_block.begin(), decoded_block.end());
}
return result;
}
static vector<char> DecompressChunk(const vector<char> &compressed_data, const string &compressor,
idx_t expected_size) {
auto compressor_id = ParseCompressorId(compressor);
if (compressor_id.empty()) {
if (compressed_data.size() != expected_size) {
throw InvalidInputException("Uncompressed Zarr chunk size mismatch: expected %llu bytes, got %llu bytes",
expected_size, compressed_data.size());
}
return compressed_data;
}
if (compressor_id != "gzip") {
if (compressor_id == "blosc") {
return DecompressBloscChunk(compressed_data, compressor, expected_size);
}
throw InvalidInputException("Unsupported Zarr compressor for zarr_cells: %s", compressor_id);
}
vector<char> decompressed(expected_size);
MiniZStream stream;
stream.Decompress(compressed_data.data(), compressed_data.size(), decompressed.data(), decompressed.size());
return decompressed;
}
static bool HasMaterializedFillValue(const ZarrArrayEntry &array) {
return !array.fill_value.empty() && array.fill_value != "null";
}
static Value ParseFillValue(const ZarrArrayEntry &array, const ZarrNumericType &dtype) {
if (!HasMaterializedFillValue(array)) {
return Value();
}
unique_ptr<yyjson_doc, decltype(&yyjson_doc_free)> doc(
yyjson_read(array.fill_value.c_str(), array.fill_value.size(), 0), yyjson_doc_free);
if (!doc) {
throw InvalidInputException("Failed to parse Zarr fill_value for array: %s", array.array_path);
}
auto root = yyjson_doc_get_root(doc.get());
if (yyjson_is_null(root)) {
return Value();
}
if (dtype.is_boolean) {
if (yyjson_is_bool(root)) {
return Value::BOOLEAN(yyjson_get_bool(root));
}
if (yyjson_is_uint(root)) {
return Value::BOOLEAN(unsafe_yyjson_get_uint(root) != 0);
}
if (yyjson_is_sint(root)) {
return Value::BOOLEAN(unsafe_yyjson_get_sint(root) != 0);
}
throw InvalidInputException("Unsupported boolean fill_value for array: %s", array.array_path);
}
if (dtype.is_float) {
double fill_value;
if (yyjson_is_real(root)) {
fill_value = unsafe_yyjson_get_real(root);
} else if (yyjson_is_uint(root)) {
fill_value = static_cast<double>(unsafe_yyjson_get_uint(root));
} else if (yyjson_is_sint(root)) {
fill_value = static_cast<double>(unsafe_yyjson_get_sint(root));
} else {
throw InvalidInputException("Unsupported floating-point fill_value for array: %s", array.array_path);
}
return dtype.element_size == 8 ? Value::DOUBLE(fill_value) : Value::FLOAT(static_cast<float>(fill_value));
}
if (dtype.is_signed) {
int64_t fill_value;
if (yyjson_is_sint(root)) {
fill_value = unsafe_yyjson_get_sint(root);
} else if (yyjson_is_uint(root)) {
fill_value = NumericCast<int64_t>(unsafe_yyjson_get_uint(root));
} else {
throw InvalidInputException("Unsupported signed integer fill_value for array: %s", array.array_path);
}
switch (dtype.element_size) {
case 1:
return Value::TINYINT(NumericCast<int8_t>(fill_value));
case 2:
return Value::SMALLINT(NumericCast<int16_t>(fill_value));
case 4:
return Value::INTEGER(NumericCast<int32_t>(fill_value));
case 8:
return Value::BIGINT(fill_value);
default:
break;
}
}
if (dtype.is_unsigned) {
uint64_t fill_value;
if (yyjson_is_uint(root)) {
fill_value = unsafe_yyjson_get_uint(root);
} else if (yyjson_is_sint(root)) {
auto signed_value = unsafe_yyjson_get_sint(root);
if (signed_value < 0) {
throw InvalidInputException("Unsigned integer fill_value cannot be negative for array: %s",
array.array_path);
}
fill_value = NumericCast<uint64_t>(signed_value);
} else {
throw InvalidInputException("Unsupported unsigned integer fill_value for array: %s", array.array_path);
}
switch (dtype.element_size) {
case 1:
return Value::UTINYINT(NumericCast<uint8_t>(fill_value));
case 2:
return Value::USMALLINT(NumericCast<uint16_t>(fill_value));
case 4:
return Value::UINTEGER(NumericCast<uint32_t>(fill_value));
case 8:
return Value::UBIGINT(fill_value);
default:
break;
}
}
throw InvalidInputException("Unsupported fill_value type for array: %s", array.array_path);
}
static const ZarrArrayEntry &FindArrayEntry(const vector<ZarrArrayEntry> &arrays, const string &array_path) {
for (idx_t i = 0; i < arrays.size(); i++) {
if (arrays[i].array_path == array_path) {
return arrays[i];
}
}
throw InvalidInputException("Zarr array \"%s\" was not found in the store", array_path);
}
static bool MatchesFilter(const TableFilter &filter, const Value &value) {
switch (filter.filter_type) {
case TableFilterType::CONSTANT_COMPARISON:
return filter.Cast<ConstantFilter>().Compare(value);
case TableFilterType::IS_NULL:
return value.IsNull();
case TableFilterType::IS_NOT_NULL:
return !value.IsNull();
case TableFilterType::IN_FILTER: {
auto &in_filter = filter.Cast<InFilter>();
for (idx_t i = 0; i < in_filter.values.size(); i++) {
if (Value::NotDistinctFrom(value, in_filter.values[i])) {