forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathASTIdentifier.cpp
More file actions
526 lines (479 loc) · 18.7 KB
/
Copy pathASTIdentifier.cpp
File metadata and controls
526 lines (479 loc) · 18.7 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
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTJSONHelpers.h>
#include <Parsers/ASTJSONReadHelpers.h>
#include <IO/ReadHelpers.h>
#include <Common/SipHash.h>
#include <IO/WriteBufferFromString.h>
#include <IO/WriteHelpers.h>
#include <Interpreters/IdentifierSemantic.h>
#include <Interpreters/StorageID.h>
#include <Parsers/ExpressionElementParsers.h>
#include <IO/Operators.h>
namespace DB
{
namespace ErrorCodes
{
extern const int UNEXPECTED_AST_STRUCTURE;
extern const int BAD_ARGUMENTS;
}
ASTIdentifier::ASTIdentifier(const String & short_name, ASTPtr && name_param)
: full_name(short_name), name_parts{short_name}, semantic(std::make_shared<IdentifierSemanticImpl>())
{
if (!name_param)
chassert(!full_name.empty());
else
children.push_back(std::move(name_param));
}
ASTIdentifier::ASTIdentifier(std::vector<String> && name_parts_, bool special, ASTs && name_params)
: name_parts(name_parts_), semantic(std::make_shared<IdentifierSemanticImpl>())
{
chassert(!name_parts.empty());
semantic->special = special;
semantic->legacy_compound = true;
if (!name_params.empty())
{
[[maybe_unused]] size_t params = 0;
for (const auto & part [[maybe_unused]] : name_parts)
{
if (part.empty())
++params;
}
chassert(params == name_params.size());
children = std::move(name_params);
}
else
{
for (const auto & part [[maybe_unused]] : name_parts)
chassert(!part.empty());
if (!special && name_parts.size() >= 2)
semantic->table = name_parts.end()[-2];
resetFullName();
}
}
bool ASTIdentifier::isParam() const
{
return !children.empty();
}
ASTPtr ASTIdentifier::getParam() const
{
chassert(full_name.empty() && children.size() == 1);
return children.front()->clone();
}
void ASTIdentifier::writeJSON(WriteBuffer & out) const
{
JSONObjectWriter w(out, "Identifier");
/// For the parametrised form (e.g. `{x:Identifier}`), `name`/`name_parts` may contain
/// empty placeholders that correspond to `ASTQueryParameter` children. We always
/// serialize the children when present so the round-trip preserves them.
w.writeString("name", full_name);
if (name_parts.size() > 1)
{
w.writeKey("name_parts");
auto & o = w.getOut();
o << '[';
for (size_t i = 0; i < name_parts.size(); ++i)
{
if (i > 0) o << ',';
writeJSONString(name_parts[i], o, w.getFormatSettings());
}
o << ']';
}
w.writeChildren(children);
w.writeAlias(*this);
}
void ASTIdentifier::readJSON(const Poco::JSON::Object & json)
{
JSONObjectReader r(json);
children = r.readChildren();
auto parts = r.readStringArray("name_parts");
if (!parts.empty())
{
size_t empty_parts = 0;
for (const auto & part : parts)
if (part.empty())
++empty_parts;
/// Empty entries in `name_parts` are placeholders for `ASTQueryParameter` children
/// (see the parametrised-identifier ctor). If they don't match, the AST is malformed.
if (empty_parts != children.size())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"ASTIdentifier JSON has {} empty 'name_parts' placeholder(s) but {} child parameter(s) during AST JSON deserialization",
empty_parts, children.size());
/// Every placeholder child must be an `ASTQueryParameter`: visitors such as
/// `ReplaceQueryParameterVisitor::visitIdentifier` cast children to `ASTQueryParameter`
/// unconditionally, so a non-parameter child here would later throw a logical error.
for (const auto & child : children)
if (!child->as<ASTQueryParameter>())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"ASTIdentifier JSON 'name_parts' placeholder child must be an ASTQueryParameter during AST JSON deserialization");
name_parts = std::move(parts);
/// Match the parametrised-compound ctor: leave `full_name` empty when there are
/// query-parameter children, otherwise compute it from `name_parts`.
if (children.empty())
resetFullName();
else
full_name.clear();
/// Restore the semantic invariants the compound `ASTIdentifier` ctor establishes:
/// a compound identifier (>= 2 parts) is a legacy compound, and for the
/// non-parametrised case the qualifier (`table`) is the second-to-last part.
/// Visitors rely on this via `supposedToBeCompound`/`restoreTable`/`IdentifierSemantic`.
if (name_parts.size() >= 2)
{
semantic->legacy_compound = true;
if (children.empty())
semantic->table = name_parts.end()[-2];
}
}
else
{
String name = r.getString("name");
if (name.empty())
{
/// Empty short name is only valid for a single-parameter identifier (`{x:Identifier}`).
/// The child must be an `ASTQueryParameter`, like the compound placeholder branch above:
/// `ReplaceQueryParameterVisitor::visitIdentifier` casts it unconditionally, so a literal
/// or function child here would later throw a logical error.
if (children.size() != 1)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"ASTIdentifier JSON with empty 'name' must have exactly one parameter child, got {}",
children.size());
if (!children[0]->as<ASTQueryParameter>())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"ASTIdentifier JSON with empty 'name' must have an ASTQueryParameter child during AST JSON deserialization");
full_name.clear();
name_parts = {""};
}
else
{
if (!children.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"ASTIdentifier JSON with non-empty 'name' must not have parameter children, got {}",
children.size());
setShortName(name);
}
}
r.readAlias(*this);
}
ASTPtr ASTIdentifier::clone() const
{
auto ret = make_intrusive<ASTIdentifier>(*this);
ret->semantic = std::make_shared<IdentifierSemanticImpl>(*ret->semantic);
ret->cloneChildren();
return ret;
}
bool ASTIdentifier::supposedToBeCompound() const
{
return semantic->legacy_compound;
}
void ASTIdentifier::setShortName(const String & new_name)
{
chassert(!new_name.empty());
full_name = new_name;
name_parts = {new_name};
bool special = semantic->special;
auto table = semantic->table;
*semantic = IdentifierSemanticImpl();
semantic->special = special;
semantic->table = table;
}
void ASTIdentifier::updateTreeHashImpl(SipHash & hash_state, bool ignore_aliases) const
{
ASTWithAlias::updateTreeHashImpl(hash_state, ignore_aliases);
}
const String & ASTIdentifier::name() const
{
if (children.empty())
{
chassert(!name_parts.empty());
chassert(!full_name.empty());
}
return full_name;
}
void ASTIdentifier::formatImplWithoutAlias(WriteBuffer & ostr, const FormatSettings & settings, FormatState & state, FormatStateStacked frame) const
{
auto format_element = [&](const String & elem_name)
{
if (auto special_delimiter_and_identifier = ParserCompoundIdentifier::splitSpecialDelimiterAndIdentifierIfAny(elem_name))
{
ostr << special_delimiter_and_identifier->first;
settings.writeIdentifier(ostr, special_delimiter_and_identifier->second, /*ambiguous=*/false);
}
else
{
settings.writeIdentifier(ostr, elem_name, /*ambiguous=*/false);
}
};
if (compound())
{
for (size_t i = 0, j = 0, size = name_parts.size(); i < size; ++i)
{
if (i != 0)
ostr << '.';
/// Some AST rewriting code, like IdentifierSemantic::setColumnLongName,
/// does not respect children of identifier.
/// Here we also ignore children if they are empty.
if (name_parts[i].empty() && j < children.size())
{
children[j]->format(ostr, settings, state, frame);
++j;
}
else
format_element(name_parts[i]);
}
}
else
{
const auto & name = shortName();
if (name.empty() && !children.empty())
children.front()->format(ostr, settings, state, frame);
else
format_element(name);
}
}
void ASTIdentifier::appendColumnNameImpl(WriteBuffer & ostr) const
{
writeString(name(), ostr);
}
void ASTIdentifier::restoreTable()
{
if (!compound())
{
name_parts.insert(name_parts.begin(), semantic->table);
resetFullName();
}
}
boost::intrusive_ptr<ASTTableIdentifier> ASTIdentifier::createTable() const
{
/// A parameterized name is not resolvable: the rebuilt identifier below would drop the
/// parameter expressions and keep only their empty-string placeholders.
if (isParam())
return nullptr;
if (name_parts.size() == 1) return make_intrusive<ASTTableIdentifier>(name_parts[0]);
if (name_parts.size() == 2) return make_intrusive<ASTTableIdentifier>(name_parts[0], name_parts[1]);
return nullptr;
}
void ASTIdentifier::resetFullName()
{
full_name = name_parts[0];
for (size_t i = 1; i < name_parts.size(); ++i)
full_name += '.' + name_parts[i];
}
ASTTableIdentifier::ASTTableIdentifier(const String & table_name, ASTs && name_params)
: ASTIdentifier({table_name}, true, std::move(name_params))
{
}
ASTTableIdentifier::ASTTableIdentifier(const StorageID & table_id, ASTs && name_params)
: ASTIdentifier(
table_id.database_name.empty() ? std::vector<String>{table_id.table_name}
: std::vector<String>{table_id.database_name, table_id.table_name},
true, std::move(name_params))
{
uuid = table_id.uuid;
}
ASTTableIdentifier::ASTTableIdentifier(const String & database_name, const String & table_name, ASTs && name_params)
: ASTIdentifier({database_name, table_name}, true, std::move(name_params))
{
}
void ASTTableIdentifier::writeJSON(WriteBuffer & out) const
{
JSONObjectWriter w(out, "TableIdentifier");
/// Mirror `ASTIdentifier`: serialize children when present so parametrised
/// forms round-trip without loss.
w.writeString("name", full_name);
if (name_parts.size() > 1)
{
w.writeKey("name_parts");
auto & o = w.getOut();
o << '[';
for (size_t i = 0; i < name_parts.size(); ++i)
{
if (i > 0) o << ',';
writeJSONString(name_parts[i], o, w.getFormatSettings());
}
o << ']';
}
if (uuid != UUIDHelpers::Nil)
{
/// A nested `ASTTableIdentifier` can carry a `UUID` from the parser (e.g. a `REFRESH DEPENDS ON src UUID '...'`
/// dependency), but a table reference is formatted through `ASTIdentifier::formatImplWithoutAlias`, which never
/// emits a `UUID` clause. `readJSON` therefore rejects a `UUID`-bearing reference (see the paired guard there),
/// so emitting `"uuid"` here would produce JSON that `formatQueryFromJSON` / `clickhouse_json` cannot read back.
/// Fail closed at serialization instead, honouring the contract that `parseQueryToJSON` rejects unsupported
/// shapes rather than emitting unreadable JSON.
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"A nested table reference with a UUID cannot be represented as AST JSON: it cannot be formatted back to SQL "
"faithfully during AST JSON serialization");
}
w.writeChildren(children);
w.writeAlias(*this);
}
void ASTTableIdentifier::readJSON(const Poco::JSON::Object & json)
{
JSONObjectReader r(json);
children = r.readChildren();
auto parts = r.readStringArray("name_parts");
if (!parts.empty())
{
size_t empty_parts = 0;
for (const auto & part : parts)
if (part.empty())
++empty_parts;
if (empty_parts != children.size())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"ASTTableIdentifier JSON has {} empty 'name_parts' placeholder(s) but {} child parameter(s) during AST JSON deserialization",
empty_parts, children.size());
/// Every placeholder child must be an `ASTQueryParameter` (see `ASTIdentifier::readJSON`).
for (const auto & child : children)
if (!child->as<ASTQueryParameter>())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"ASTTableIdentifier JSON 'name_parts' placeholder child must be an ASTQueryParameter during AST JSON deserialization");
name_parts = std::move(parts);
/// `ASTTableIdentifier` can only represent a one- or two-part table name
/// (`table` or `database.table`): `ParserCompoundIdentifier` rejects `parts.size() > 2`
/// for table identifiers. `getTableId`/`getDatabaseName` would otherwise mis-resolve a
/// longer name (treating `db.tbl.extra` as the single table `db`), formatting a different
/// target than execution uses. Reject the parser-impossible shape at the JSON boundary.
if (name_parts.size() > 2)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"ASTTableIdentifier JSON 'name_parts' has {} parts, but a table identifier accepts at most 2 during AST JSON deserialization",
name_parts.size());
if (children.empty())
resetFullName();
else
full_name.clear();
/// Mirror the compound ctor: a table identifier is always `special`, so it is a
/// legacy compound when it has >= 2 parts, but the `table` qualifier is not stored.
if (name_parts.size() >= 2)
semantic->legacy_compound = true;
}
else
{
String name = r.getString("name");
if (name.empty())
{
/// As in `ASTIdentifier::readJSON`, the single child of an empty-name identifier must be an
/// `ASTQueryParameter`; query-parameter visitors downcast it unconditionally.
if (children.size() != 1)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"ASTTableIdentifier JSON with empty 'name' must have exactly one parameter child, got {}",
children.size());
if (!children[0]->as<ASTQueryParameter>())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"ASTTableIdentifier JSON with empty 'name' must have an ASTQueryParameter child during AST JSON deserialization");
full_name.clear();
name_parts = {""};
}
else
{
if (!children.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"ASTTableIdentifier JSON with non-empty 'name' must not have parameter children, got {}",
children.size());
setShortName(name);
}
}
if (r.has("uuid"))
{
/// A nested `ASTTableIdentifier` can carry a `UUID` from the parser (e.g. a `REFRESH DEPENDS ON src UUID '...'`
/// dependency), and `getTableId` feeds that `UUID` into the executed `StorageID`. But a table reference is
/// formatted through `ASTIdentifier::formatImplWithoutAlias`, which never emits a `UUID` clause, so
/// `formatQueryFromJSON` would print a name-only reference while the JSON AST still resolves the table by
/// `UUID`. Reject the `UUID`-bearing nested reference at the boundary (fail closed) rather than hiding
/// semantic state behind a lossy round trip.
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"ASTTableIdentifier JSON must not carry a 'uuid': a nested table reference with a UUID cannot be "
"formatted back to SQL faithfully during AST JSON deserialization");
}
r.readAlias(*this);
}
ASTPtr ASTTableIdentifier::clone() const
{
auto ret = make_intrusive<ASTTableIdentifier>(*this);
ret->semantic = std::make_shared<IdentifierSemanticImpl>(*ret->semantic);
ret->cloneChildren();
return ret;
}
StorageID ASTTableIdentifier::getTableId() const
{
if (name_parts.size() == 2) return {name_parts[0], name_parts[1], uuid};
return {{}, name_parts[0], uuid};
}
String ASTTableIdentifier::getDatabaseName() const
{
if (name_parts.size() == 2) return name_parts[0];
return {};
}
ASTPtr ASTTableIdentifier::getTable() const
{
if (name_parts.size() == 2)
{
if (!name_parts[1].empty())
return make_intrusive<ASTIdentifier>(name_parts[1]);
if (name_parts[0].empty())
return make_intrusive<ASTIdentifier>("", children[1]->clone());
return make_intrusive<ASTIdentifier>("", children[0]->clone());
}
if (name_parts.size() == 1)
{
if (name_parts[0].empty())
return make_intrusive<ASTIdentifier>("", children[0]->clone());
return make_intrusive<ASTIdentifier>(name_parts[0]);
}
return {};
}
ASTPtr ASTTableIdentifier::getDatabase() const
{
if (name_parts.size() == 2)
{
if (name_parts[0].empty())
return make_intrusive<ASTIdentifier>("", children[0]->clone());
return make_intrusive<ASTIdentifier>(name_parts[0]);
}
return {};
}
void ASTTableIdentifier::resetTable(const String & database_name, const String & table_name)
{
auto identifier = make_intrusive<ASTTableIdentifier>(StorageID{database_name, table_name});
full_name.swap(identifier->full_name);
name_parts.swap(identifier->name_parts);
uuid = identifier->uuid;
}
void ASTTableIdentifier::updateTreeHashImpl(SipHash & hash_state, bool ignore_aliases) const
{
hash_state.update(uuid);
ASTIdentifier::updateTreeHashImpl(hash_state, ignore_aliases);
}
String getIdentifierName(const IAST * ast)
{
String res;
if (tryGetIdentifierNameInto(ast, res))
return res;
if (ast)
throw Exception(ErrorCodes::UNEXPECTED_AST_STRUCTURE, "{} is not an identifier", ast->formatForErrorMessage());
throw Exception(ErrorCodes::UNEXPECTED_AST_STRUCTURE, "AST node is nullptr");
}
std::optional<String> tryGetIdentifierName(const IAST * ast)
{
String res;
if (tryGetIdentifierNameInto(ast, res))
return res;
return {};
}
bool tryGetIdentifierNameInto(const IAST * ast, String & name)
{
if (ast)
{
if (const auto * node = dynamic_cast<const ASTIdentifier *>(ast))
{
name = node->name();
return true;
}
}
return false;
}
void setIdentifierSpecial(ASTPtr & ast)
{
if (ast)
if (auto * id = ast->as<ASTIdentifier>())
id->semantic->special = true;
}
}