forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathISerialization.cpp
More file actions
545 lines (463 loc) · 18.4 KB
/
ISerialization.cpp
File metadata and controls
545 lines (463 loc) · 18.4 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
#include <Columns/ColumnBLOB.h>
#include <Columns/IColumn.h>
#include <Compression/CompressionFactory.h>
#include <DataTypes/NestedUtils.h>
#include <DataTypes/Serializations/ISerialization.h>
#include <IO/Operators.h>
#include <IO/ReadBufferFromString.h>
#include <IO/WriteHelpers.h>
#include <base/EnumReflection.h>
#include <Common/escapeForFileName.h>
#include <Common/typeid_cast.h>
namespace DB
{
namespace ErrorCodes
{
extern const int MULTIPLE_STREAMS_REQUIRED;
extern const int UNEXPECTED_DATA_AFTER_PARSED_VALUE;
extern const int LOGICAL_ERROR;
}
ISerialization::Kind ISerialization::getKind(const IColumn & column)
{
if (column.isSparse())
return Kind::SPARSE;
if (const auto * column_blob = typeid_cast<const ColumnBLOB *>(&column))
return column_blob->wrappedColumnIsSparse() ? Kind::DETACHED_OVER_SPARSE : Kind::DETACHED;
return Kind::DEFAULT;
}
String ISerialization::kindToString(Kind kind)
{
switch (kind)
{
case Kind::DEFAULT:
return "Default";
case Kind::SPARSE:
return "Sparse";
case Kind::DETACHED:
return "Detached";
case Kind::DETACHED_OVER_SPARSE:
return "DetachedOverSparse";
}
}
ISerialization::Kind ISerialization::stringToKind(const String & str)
{
if (str == "Default")
return Kind::DEFAULT;
else if (str == "Sparse")
return Kind::SPARSE;
else if (str == "Detached")
return Kind::DETACHED;
else if (str == "DetachedOverSparse")
return Kind::DETACHED_OVER_SPARSE;
throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown serialization kind '{}'", str);
}
const std::set<SubstreamType> ISerialization::Substream::named_types
{
TupleElement,
NamedOffsets,
NamedNullMap,
NamedVariantDiscriminators,
};
String ISerialization::Substream::toString() const
{
if (named_types.contains(type))
return fmt::format("{}({})", type, name_of_substream);
if (type == VariantElement)
return fmt::format("VariantElement({})", variant_element_name);
if (type == VariantElementNullMap)
return fmt::format("VariantElementNullMap({}.null)", variant_element_name);
return String(magic_enum::enum_name(type));
}
String ISerialization::SubstreamPath::toString() const
{
WriteBufferFromOwnString wb;
wb << "{";
for (size_t i = 0; i < size(); ++i)
{
if (i != 0)
wb << ", ";
wb << at(i).toString();
}
wb << "}";
return wb.str();
}
void ISerialization::enumerateStreams(
EnumerateStreamsSettings & settings,
const StreamCallback & callback,
const SubstreamData & data) const
{
settings.path.push_back(Substream::Regular);
settings.path.back().data = data;
callback(settings.path);
settings.path.pop_back();
}
void ISerialization::enumerateStreams(
const StreamCallback & callback,
const DataTypePtr & type,
const ColumnPtr & column) const
{
EnumerateStreamsSettings settings;
auto data = SubstreamData(getPtr()).withType(type).withColumn(column);
enumerateStreams(settings, callback, data);
}
void ISerialization::serializeBinaryBulk(const IColumn & column, WriteBuffer &, size_t, size_t) const
{
throw Exception(ErrorCodes::MULTIPLE_STREAMS_REQUIRED, "Column {} must be serialized with multiple streams", column.getName());
}
void ISerialization::deserializeBinaryBulk(IColumn & column, ReadBuffer &, size_t, size_t, double) const
{
throw Exception(ErrorCodes::MULTIPLE_STREAMS_REQUIRED, "Column {} must be deserialized with multiple streams", column.getName());
}
void ISerialization::serializeBinaryBulkWithMultipleStreams(
const IColumn & column,
size_t offset,
size_t limit,
SerializeBinaryBulkSettings & settings,
SerializeBinaryBulkStatePtr & /* state */) const
{
settings.path.push_back(Substream::Regular);
if (WriteBuffer * stream = settings.getter(settings.path))
serializeBinaryBulk(column, *stream, offset, limit);
settings.path.pop_back();
}
void ISerialization::deserializeBinaryBulkWithMultipleStreams(
ColumnPtr & column,
size_t rows_offset,
size_t limit,
DeserializeBinaryBulkSettings & settings,
DeserializeBinaryBulkStatePtr & /* state */,
SubstreamsCache * cache) const
{
settings.path.push_back(Substream::Regular);
auto cached_column = getFromSubstreamsCache(cache, settings.path);
if (cached_column)
{
column = cached_column;
}
else if (ReadBuffer * stream = settings.getter(settings.path))
{
auto mutable_column = column->assumeMutable();
deserializeBinaryBulk(*mutable_column, *stream, rows_offset, limit, settings.avg_value_size_hint);
column = std::move(mutable_column);
addToSubstreamsCache(cache, settings.path, column);
}
settings.path.pop_back();
}
namespace
{
using SubstreamIterator = ISerialization::SubstreamPath::const_iterator;
String getNameForSubstreamPath(
String stream_name,
SubstreamIterator begin,
SubstreamIterator end,
bool escape_for_file_name)
{
using Substream = ISerialization::Substream;
size_t array_level = 0;
for (auto it = begin; it != end; ++it)
{
if (it->type == Substream::NullMap)
stream_name += ".null";
else if (it->type == Substream::ArraySizes)
stream_name += ".size" + toString(array_level);
else if (it->type == Substream::ArrayElements)
++array_level;
else if (it->type == Substream::DictionaryKeys)
stream_name += ".dict";
else if (it->type == Substream::DictionaryKeysPrefix)
stream_name += ".dict_prefix";
else if (it->type == Substream::SparseOffsets)
stream_name += ".sparse.idx";
else if (Substream::named_types.contains(it->type))
{
auto substream_name = "." + it->name_of_substream;
/// For compatibility reasons, we use %2E (escaped dot) instead of dot.
/// Because nested data may be represented not by Array of Tuple,
/// but by separate Array columns with names in a form of a.b,
/// and name is encoded as a whole.
if (it->type == Substream::TupleElement && escape_for_file_name)
stream_name += escapeForFileName(substream_name);
else
stream_name += substream_name;
}
else if (it->type == Substream::VariantDiscriminators)
stream_name += ".variant_discr";
else if (it->type == Substream::VariantDiscriminatorsPrefix)
stream_name += ".variant_discr_prefix";
else if (it->type == Substream::VariantOffsets)
stream_name += ".variant_offsets";
else if (it->type == Substream::VariantElement)
stream_name += "." + it->variant_element_name;
else if (it->type == Substream::VariantElementNullMap)
stream_name += "." + it->variant_element_name + ".null";
else if (it->type == SubstreamType::DynamicStructure)
stream_name += ".dynamic_structure";
else if (it->type == SubstreamType::ObjectStructure)
stream_name += ".object_structure";
else if (it->type == SubstreamType::ObjectSharedData)
stream_name += ".object_shared_data";
else if (it->type == SubstreamType::ObjectTypedPath || it->type == SubstreamType::ObjectDynamicPath)
stream_name += "." + (escape_for_file_name ? escapeForFileName(it->object_path_name) : it->object_path_name);
}
return stream_name;
}
}
String ISerialization::getFileNameForStream(const NameAndTypePair & column, const SubstreamPath & path)
{
return getFileNameForStream(column.getNameInStorage(), path);
}
static bool isPossibleOffsetsOfNested(const ISerialization::SubstreamPath & path)
{
/// Arrays of Nested cannot be inside other types.
/// So it's ok to check only first element of path.
/// Array offsets as a part of serialization of Array type.
if (path.size() == 1
&& path[0].type == ISerialization::Substream::ArraySizes)
return true;
/// Array offsets as a separate subcolumn.
if (path.size() == 2
&& path[0].type == ISerialization::Substream::NamedOffsets
&& path[1].type == ISerialization::Substream::Regular
&& path[0].name_of_substream == "size0")
return true;
return false;
}
String ISerialization::getFileNameForStream(const String & name_in_storage, const SubstreamPath & path)
{
String stream_name;
auto nested_storage_name = Nested::extractTableName(name_in_storage);
if (name_in_storage != nested_storage_name && isPossibleOffsetsOfNested(path))
stream_name = escapeForFileName(nested_storage_name);
else
stream_name = escapeForFileName(name_in_storage);
return getNameForSubstreamPath(std::move(stream_name), path.begin(), path.end(), true);
}
String ISerialization::getFileNameForRenamedColumnStream(const String & name_from, const String & name_to, const String & file_name)
{
auto name_from_escaped = escapeForFileName(name_from);
if (file_name.starts_with(name_from_escaped))
return escapeForFileName(name_to) + file_name.substr(0, name_from_escaped.size());
auto nested_storage_name_escaped = escapeForFileName(Nested::extractTableName(name_from));
if (file_name.starts_with(nested_storage_name_escaped))
return escapeForFileName(Nested::extractTableName(name_to)) + file_name.substr(0, nested_storage_name_escaped.size());
throw Exception(ErrorCodes::LOGICAL_ERROR, "File name {} doesn't correspond to column {}", file_name, name_from);
}
String ISerialization::getFileNameForRenamedColumnStream(const NameAndTypePair & column_from, const NameAndTypePair & column_to, const String & file_name)
{
return getFileNameForRenamedColumnStream(column_from.getNameInStorage(), column_to.getNameInStorage(), file_name);
}
String ISerialization::getSubcolumnNameForStream(const SubstreamPath & path)
{
return getSubcolumnNameForStream(path, path.size());
}
String ISerialization::getSubcolumnNameForStream(const SubstreamPath & path, size_t prefix_len)
{
auto subcolumn_name = getNameForSubstreamPath("", path.begin(), path.begin() + prefix_len, false);
if (!subcolumn_name.empty())
subcolumn_name = subcolumn_name.substr(1); // It starts with a dot.
return subcolumn_name;
}
void ISerialization::addToSubstreamsCache(SubstreamsCache * cache, const SubstreamPath & path, ColumnPtr column)
{
if (!cache || path.empty())
return;
cache->emplace(getSubcolumnNameForStream(path), column);
}
ColumnPtr ISerialization::getFromSubstreamsCache(SubstreamsCache * cache, const SubstreamPath & path)
{
if (!cache || path.empty())
return nullptr;
auto it = cache->find(getSubcolumnNameForStream(path));
return it == cache->end() ? nullptr : it->second;
}
void ISerialization::addToSubstreamsDeserializeStatesCache(SubstreamsDeserializeStatesCache * cache, const SubstreamPath & path, DeserializeBinaryBulkStatePtr state)
{
if (!cache || path.empty())
return;
cache->emplace(getSubcolumnNameForStream(path), state);
}
ISerialization::DeserializeBinaryBulkStatePtr ISerialization::getFromSubstreamsDeserializeStatesCache(SubstreamsDeserializeStatesCache * cache, const SubstreamPath & path)
{
if (!cache || path.empty())
return nullptr;
auto it = cache->find(getSubcolumnNameForStream(path));
return it == cache->end() ? nullptr : it->second;
}
bool ISerialization::isSpecialCompressionAllowed(const SubstreamPath & path)
{
for (const auto & elem : path)
{
if (elem.type == Substream::NullMap
|| elem.type == Substream::ArraySizes
|| elem.type == Substream::DictionaryIndexes
|| elem.type == Substream::SparseOffsets)
return false;
}
return true;
}
namespace
{
template <typename F>
bool tryDeserializeText(const F deserialize, DB::IColumn & column)
{
size_t prev_size = column.size();
try
{
deserialize(column);
return true;
}
catch (...)
{
if (column.size() > prev_size)
column.popBack(column.size() - prev_size);
return false;
}
}
}
bool ISerialization::tryDeserializeTextCSV(DB::IColumn & column, DB::ReadBuffer & istr, const DB::FormatSettings & settings) const
{
return tryDeserializeText([&](DB::IColumn & my_column) { deserializeTextCSV(my_column, istr, settings); }, column);
}
bool ISerialization::tryDeserializeTextEscaped(DB::IColumn & column, DB::ReadBuffer & istr, const DB::FormatSettings & settings) const
{
return tryDeserializeText([&](DB::IColumn & my_column) { deserializeTextEscaped(my_column, istr, settings); }, column);
}
bool ISerialization::tryDeserializeTextJSON(DB::IColumn & column, DB::ReadBuffer & istr, const DB::FormatSettings & settings) const
{
return tryDeserializeText([&](DB::IColumn & my_column) { deserializeTextJSON(my_column, istr, settings); }, column);
}
bool ISerialization::tryDeserializeTextQuoted(DB::IColumn & column, DB::ReadBuffer & istr, const DB::FormatSettings & settings) const
{
return tryDeserializeText([&](DB::IColumn & my_column) { deserializeTextQuoted(my_column, istr, settings); }, column);
}
bool ISerialization::tryDeserializeWholeText(DB::IColumn & column, DB::ReadBuffer & istr, const DB::FormatSettings & settings) const
{
return tryDeserializeText([&](DB::IColumn & my_column) { deserializeWholeText(my_column, istr, settings); }, column);
}
void ISerialization::deserializeTextRaw(IColumn & column, ReadBuffer & istr, const FormatSettings & settings) const
{
String field;
/// Read until \t or \n.
readString(field, istr);
ReadBufferFromString buf(field);
deserializeWholeText(column, buf, settings);
}
bool ISerialization::tryDeserializeTextRaw(IColumn & column, ReadBuffer & istr, const FormatSettings & settings) const
{
String field;
/// Read until \t or \n.
readString(field, istr);
ReadBufferFromString buf(field);
return tryDeserializeWholeText(column, buf, settings);
}
void ISerialization::serializeTextMarkdown(
const DB::IColumn & column, size_t row_num, DB::WriteBuffer & ostr, const DB::FormatSettings & settings) const
{
serializeTextEscaped(column, row_num, ostr, settings);
}
void ISerialization::serializeTextRaw(const IColumn & column, size_t row_num, WriteBuffer & ostr, const FormatSettings & settings) const
{
serializeText(column, row_num, ostr, settings);
}
size_t ISerialization::getArrayLevel(const SubstreamPath & path)
{
size_t level = 0;
for (const auto & elem : path)
level += elem.type == Substream::ArrayElements;
return level;
}
bool ISerialization::hasSubcolumnForPath(const SubstreamPath & path, size_t prefix_len)
{
if (prefix_len == 0 || prefix_len > path.size())
return false;
size_t last_elem = prefix_len - 1;
return path[last_elem].type == Substream::NullMap
|| path[last_elem].type == Substream::TupleElement
|| path[last_elem].type == Substream::ArraySizes
|| path[last_elem].type == Substream::VariantElement
|| path[last_elem].type == Substream::VariantElementNullMap
|| path[last_elem].type == Substream::ObjectTypedPath;
}
bool ISerialization::isEphemeralSubcolumn(const DB::ISerialization::SubstreamPath & path, size_t prefix_len)
{
if (prefix_len == 0 || prefix_len > path.size())
return false;
size_t last_elem = prefix_len - 1;
return path[last_elem].type == Substream::VariantElementNullMap;
}
bool ISerialization::isDynamicSubcolumn(const DB::ISerialization::SubstreamPath & path, size_t prefix_len)
{
if (prefix_len == 0 || prefix_len > path.size())
return false;
for (size_t i = 0; i != prefix_len; ++i)
{
if (path[i].type == SubstreamType::DynamicData || path[i].type == SubstreamType::DynamicStructure
|| path[i].type == SubstreamType::ObjectData || path[i].type == SubstreamType::ObjectStructure)
return true;
}
return false;
}
bool ISerialization::isLowCardinalityDictionarySubcolumn(const DB::ISerialization::SubstreamPath & path)
{
if (path.empty())
return false;
return path[path.size() - 1].type == SubstreamType::DictionaryKeys;
}
bool ISerialization::isDynamicOrObjectStructureSubcolumn(const DB::ISerialization::SubstreamPath & path)
{
if (path.empty())
return false;
return path[path.size() - 1].type == SubstreamType::DynamicStructure || path[path.size() - 1].type == SubstreamType::ObjectStructure;
}
bool ISerialization::hasPrefix(const DB::ISerialization::SubstreamPath & path, bool use_specialized_prefixes_substreams)
{
if (path.empty())
return false;
switch (path[path.size() - 1].type)
{
case SubstreamType::DynamicStructure: [[fallthrough]];
case SubstreamType::ObjectStructure: [[fallthrough]];
case SubstreamType::DeprecatedObjectStructure: [[fallthrough]];
case SubstreamType::DictionaryKeysPrefix: [[fallthrough]];
case SubstreamType::VariantDiscriminatorsPrefix:
return true;
case SubstreamType::DictionaryKeys: [[fallthrough]];
case SubstreamType::VariantDiscriminators:
return !use_specialized_prefixes_substreams;
default:
return false;
}
}
ISerialization::SubstreamData ISerialization::createFromPath(const SubstreamPath & path, size_t prefix_len)
{
assert(prefix_len <= path.size());
if (prefix_len == 0)
return {};
ssize_t last_elem = prefix_len - 1;
auto res = path[last_elem].data;
for (ssize_t i = last_elem - 1; i >= 0; --i)
{
const auto & creator = path[i].creator;
if (creator)
{
res.serialization = res.serialization ? creator->create(res.serialization, res.type) : res.serialization;
res.type = res.type ? creator->create(res.type) : res.type;
res.column = res.column ? creator->create(res.column) : res.column;
}
}
return res;
}
void ISerialization::throwUnexpectedDataAfterParsedValue(IColumn & column, ReadBuffer & istr, const FormatSettings & settings, const String & type_name) const
{
WriteBufferFromOwnString ostr;
serializeText(column, column.size() - 1, ostr, settings);
/// Restore correct column size.
column.popBack(1);
throw Exception(
ErrorCodes::UNEXPECTED_DATA_AFTER_PARSED_VALUE,
"Unexpected data '{}' after parsed {} value '{}'",
std::string(istr.position(), std::min(size_t(10), istr.available())),
type_name,
ostr.str());
}
}