forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataTypeFactory.cpp
More file actions
419 lines (360 loc) · 13.9 KB
/
Copy pathDataTypeFactory.cpp
File metadata and controls
419 lines (360 loc) · 13.9 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
#include <DataTypes/DataTypeFactory.h>
#include <DataTypes/DataTypeCustom.h>
#include <DataTypes/DataTypeEnum.h>
#include <DataTypes/DataTypeTuple.h>
#include <Parsers/parseQuery.h>
#include <Parsers/ParserCreateQuery.h>
#include <Parsers/ASTDataType.h>
#include <Parsers/ASTEnumDataType.h>
#include <Parsers/ASTTupleDataType.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTLiteral.h>
#include <Common/typeid_cast.h>
#include <Poco/String.h>
#include <Common/StringUtils.h>
#include <IO/WriteHelpers.h>
#include <Core/Defines.h>
#include <Core/Settings.h>
#include <Common/CurrentThread.h>
#include <Interpreters/Context.h>
namespace DB
{
namespace Setting
{
extern const SettingsBool log_queries;
}
namespace ErrorCodes
{
extern const int ARGUMENT_OUT_OF_BOUND;
extern const int BAD_ARGUMENTS;
extern const int LOGICAL_ERROR;
extern const int UNKNOWN_TYPE;
extern const int UNEXPECTED_AST_STRUCTURE;
extern const int DATA_TYPE_CANNOT_HAVE_ARGUMENTS;
}
template <typename FieldType>
static typename DataTypeEnum<FieldType>::Values checkAndBuildEnumValues(
const std::vector<std::pair<String, Int64>> & values, const char * type_name)
{
typename DataTypeEnum<FieldType>::Values enum_values;
enum_values.reserve(values.size());
for (const auto & [name, value] : values)
{
if (value > std::numeric_limits<FieldType>::max() || value < std::numeric_limits<FieldType>::min())
throw Exception(ErrorCodes::ARGUMENT_OUT_OF_BOUND, "Value {} for element '{}' exceeds range of {}",
value, name, type_name);
enum_values.emplace_back(name, static_cast<FieldType>(value));
}
return enum_values;
}
/// Helper to create Enum data type from ASTEnumDataType values
static DataTypePtr createEnumFromValues(const String & type_name, const std::vector<std::pair<String, Int64>> & values)
{
String type_name_upper = Poco::toUpper(type_name);
bool use_enum16 = (type_name_upper == "ENUM16");
if (!use_enum16 && type_name_upper == "ENUM")
{
/// Auto-detect Enum8 vs Enum16 based on values
for (const auto & [_, value] : values)
{
if (value < std::numeric_limits<Int8>::min() || value > std::numeric_limits<Int8>::max())
{
use_enum16 = true;
break;
}
}
}
if (use_enum16)
return std::make_shared<DataTypeEnum16>(checkAndBuildEnumValues<Int16>(values, "Enum16"));
return std::make_shared<DataTypeEnum8>(checkAndBuildEnumValues<Int8>(values, "Enum8"));
}
/// Helper to create Tuple data type from ASTTupleDataType
static DataTypePtr createTupleFromAST(const ASTTupleDataType * tuple_ast)
{
const auto arguments = tuple_ast->getArguments();
if (!arguments || arguments->children.empty())
return std::make_shared<DataTypeTuple>(DataTypes{});
DataTypes nested_types;
nested_types.reserve(arguments->children.size());
for (const auto & child : arguments->children)
nested_types.emplace_back(DataTypeFactory::instance().get(child));
/// If element_names is empty, it's an unnamed tuple
if (tuple_ast->element_names.empty())
return std::make_shared<DataTypeTuple>(nested_types);
/// Named tuple - validate all elements have names (no mixed named/unnamed)
for (const auto & elem_name : tuple_ast->element_names)
{
if (elem_name.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Names are specified not for all elements of Tuple type");
}
if (tuple_ast->element_names.size() != nested_types.size())
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Names are specified not for all elements of Tuple type");
return std::make_shared<DataTypeTuple>(nested_types, tuple_ast->element_names);
}
DataTypePtr DataTypeFactory::get(const String & full_name) const
{
return getImpl<false>(full_name);
}
DataTypePtr DataTypeFactory::tryGet(const String & full_name) const
{
return getImpl<true>(full_name);
}
template <bool nullptr_on_error>
DataTypePtr DataTypeFactory::getImpl(const String & full_name) const
{
/// Data type parser can be invoked from coroutines with small stack.
/// Value 315 is known to cause stack overflow in some test configurations (debug build, sanitizers)
/// let's make the threshold significantly lower.
/// It is impractical for user to have complex data types with this depth.
#if defined(SANITIZER) || !defined(NDEBUG)
static constexpr size_t data_type_max_parse_depth = 150;
#else
static constexpr size_t data_type_max_parse_depth = 300;
#endif
ParserDataType parser;
ASTPtr ast;
if constexpr (nullptr_on_error)
{
String out_err;
const char * start = full_name.data();
ast = tryParseQuery(parser, start, start + full_name.size(), out_err, false, "data type", false,
DBMS_DEFAULT_MAX_QUERY_SIZE, data_type_max_parse_depth, DBMS_DEFAULT_MAX_PARSER_BACKTRACKS, true);
if (!ast)
return nullptr;
}
else
{
ast = parseQuery(parser, full_name.data(), full_name.data() + full_name.size(), "data type", false, data_type_max_parse_depth, DBMS_DEFAULT_MAX_PARSER_BACKTRACKS);
}
return getImpl<nullptr_on_error>(ast);
}
DataTypePtr DataTypeFactory::get(const ASTPtr & ast) const
{
return getImpl<false>(ast);
}
DataTypePtr DataTypeFactory::tryGet(const ASTPtr & ast) const
{
return getImpl<true>(ast);
}
template <bool nullptr_on_error>
DataTypePtr DataTypeFactory::getImpl(const ASTPtr & ast) const
{
/// These specialized branches construct the type directly, bypassing the registered-creator
/// try/catch below, so they must honor nullptr_on_error themselves: tryGet promises nullptr
/// (not an exception) on invalid type text, e.g. an out-of-range enum value.
/// Handle specialized ASTEnumDataType directly
if (const auto * enum_type = ast->as<ASTEnumDataType>())
{
if constexpr (nullptr_on_error)
{
try
{
return createEnumFromValues(enum_type->name, enum_type->values);
}
catch (...) // Ok: tryGet is a try-pattern
{
return nullptr;
}
}
else
return createEnumFromValues(enum_type->name, enum_type->values);
}
/// Handle specialized ASTTupleDataType directly
if (const auto * tuple_type = ast->as<ASTTupleDataType>())
{
if constexpr (nullptr_on_error)
{
try
{
return createTupleFromAST(tuple_type);
}
catch (...) // Ok: tryGet is a try-pattern
{
return nullptr;
}
}
else
return createTupleFromAST(tuple_type);
}
if (const auto * type = ast->as<ASTDataType>())
{
return getImpl<nullptr_on_error>(type->name, type->getArguments());
}
if (const auto * ident = ast->as<ASTIdentifier>())
{
return getImpl<nullptr_on_error>(ident->name(), {});
}
if (const auto * lit = ast->as<ASTLiteral>())
{
if (lit->value.isNull())
return getImpl<nullptr_on_error>("Null", {});
}
if constexpr (nullptr_on_error)
return nullptr;
throw Exception(ErrorCodes::UNEXPECTED_AST_STRUCTURE, "Unexpected AST element for data type: {}.", ast->getID());
}
DataTypePtr DataTypeFactory::get(const String & family_name_param, const ASTPtr & parameters) const
{
return getImpl<false>(family_name_param, parameters);
}
DataTypePtr DataTypeFactory::tryGet(const String & family_name_param, const ASTPtr & parameters) const
{
return getImpl<true>(family_name_param, parameters);
}
template <bool nullptr_on_error>
DataTypePtr DataTypeFactory::getImpl(const String & family_name_param, const ASTPtr & parameters) const
{
String family_name = getAliasToOrName(family_name_param);
const auto * creator = findCreatorByName<nullptr_on_error>(family_name);
DataTypePtr data_type;
if constexpr (nullptr_on_error)
{
if (!creator)
return nullptr;
try
{
data_type = (*creator)(parameters);
}
catch (...) // Ok: tryGetDataType is a try-pattern
{
return nullptr;
}
}
else
{
chassert(creator);
data_type = (*creator)(parameters);
}
auto query_context = CurrentThread::tryGetQueryContext();
if (query_context && query_context->getSettingsRef()[Setting::log_queries])
{
query_context->addQueryFactoriesInfo(Context::QueryLogFactories::DataType, data_type->getName());
}
return data_type;
}
DataTypePtr DataTypeFactory::getCustom(DataTypeCustomDescPtr customization) const
{
if (!customization->name)
throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot create custom type without name");
auto type = get(customization->name->getName());
type->setCustomization(std::move(customization));
return type;
}
DataTypePtr DataTypeFactory::getCustom(const String & base_name, DataTypeCustomDescPtr customization) const
{
auto type = get(base_name);
type->setCustomization(std::move(customization));
return type;
}
void DataTypeFactory::registerDataType(const String & family_name, Value creator, Case case_sensitiveness, Documentation documentation)
{
if (creator == nullptr)
throw Exception(ErrorCodes::LOGICAL_ERROR, "DataTypeFactory: the data type family {} has been provided a null constructor", family_name);
String family_name_lowercase = Poco::toLower(family_name);
if (isAlias(family_name) || isAlias(family_name_lowercase))
throw Exception(ErrorCodes::LOGICAL_ERROR, "DataTypeFactory: the data type family name '{}' is already registered as alias", family_name);
if (!data_types.emplace(family_name, creator).second)
throw Exception(ErrorCodes::LOGICAL_ERROR, "DataTypeFactory: the data type family name '{}' is not unique",
family_name);
if (case_sensitiveness == Case::Insensitive
&& !case_insensitive_data_types.emplace(family_name_lowercase, creator).second)
throw Exception(ErrorCodes::LOGICAL_ERROR, "DataTypeFactory: the case insensitive data type family name '{}' is not unique", family_name);
data_type_documentations.emplace(family_name, std::move(documentation));
}
void DataTypeFactory::registerSimpleDataType(const String & name, SimpleCreator creator, Case case_sensitiveness, Documentation documentation)
{
if (creator == nullptr)
throw Exception(ErrorCodes::LOGICAL_ERROR, "DataTypeFactory: the data type {} has been provided a null constructor",
name);
registerDataType(name, [name, creator](const ASTPtr & ast)
{
if (ast)
throw Exception(ErrorCodes::DATA_TYPE_CANNOT_HAVE_ARGUMENTS, "Data type {} cannot have arguments", name);
return creator();
}, case_sensitiveness, std::move(documentation));
}
void DataTypeFactory::registerDataTypeCustom(const String & family_name, CreatorWithCustom creator, Case case_sensitiveness, Documentation documentation)
{
registerDataType(family_name, [creator](const ASTPtr & ast)
{
auto res = creator(ast);
res.first->setCustomization(std::move(res.second));
return res.first;
}, case_sensitiveness, std::move(documentation));
}
void DataTypeFactory::registerSimpleDataTypeCustom(const String & name, SimpleCreatorWithCustom creator, Case case_sensitiveness, Documentation documentation)
{
registerDataTypeCustom(name, [name, creator](const ASTPtr & ast)
{
if (ast)
throw Exception(ErrorCodes::DATA_TYPE_CANNOT_HAVE_ARGUMENTS, "Data type {} cannot have arguments", name);
return creator();
}, case_sensitiveness, std::move(documentation));
}
Documentation DataTypeFactory::getDocumentation(const String & family_name) const
{
if (auto it = data_type_documentations.find(family_name); it != data_type_documentations.end())
return it->second;
return {};
}
template <bool nullptr_on_error>
const DataTypeFactory::Value * DataTypeFactory::findCreatorByName(const String & family_name) const
{
{
DataTypesDictionary::const_iterator it = data_types.find(family_name);
if (data_types.end() != it)
{
return &it->second;
}
}
String family_name_lowercase = Poco::toLower(family_name);
{
DataTypesDictionary::const_iterator it = case_insensitive_data_types.find(family_name_lowercase);
if (case_insensitive_data_types.end() != it)
{
return &it->second;
}
}
if constexpr (nullptr_on_error)
return nullptr;
auto hints = this->getHints(family_name);
if (!hints.empty())
throw Exception(ErrorCodes::UNKNOWN_TYPE, "Unknown data type family: {}. Maybe you meant: {}", family_name, toString(hints));
throw Exception(ErrorCodes::UNKNOWN_TYPE, "Unknown data type family: {}", family_name);
}
DataTypeFactory::DataTypeFactory()
{
registerDataTypeNumbers(*this);
registerDataTypeDecimal(*this);
registerDataTypeDate(*this);
registerDataTypeDate32(*this);
registerDataTypeDateTime(*this);
registerDataTypeTime(*this);
registerDataTypeString(*this);
registerDataTypeFixedString(*this);
registerDataTypeEnum(*this);
registerDataTypeArray(*this);
registerDataTypeTuple(*this);
registerDataTypeQBit(*this);
registerDataTypeNullable(*this);
registerDataTypeNothing(*this);
registerDataTypeUUID(*this);
registerDataTypeIPv4andIPv6(*this);
registerDataTypeAggregateFunction(*this);
registerDataTypeNested(*this);
registerDataTypeInterval(*this);
registerDataTypeLowCardinality(*this);
registerDataTypeDomainBool(*this);
registerDataTypeDomainSimpleAggregateFunction(*this);
registerDataTypeDomainGeo(*this);
registerDataTypeMap(*this);
registerDataTypeVariant(*this);
registerDataTypeDynamic(*this);
registerDataTypeJSON(*this);
}
DataTypeFactory & DataTypeFactory::instance()
{
static DataTypeFactory ret;
return ret;
}
}