Repository navigation
Expand file tree
/
Copy pathClientBaseHelpers.cpp
More file actions
588 lines (505 loc) · 21.9 KB
/
Copy pathClientBaseHelpers.cpp
File metadata and controls
588 lines (505 loc) · 21.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
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
#include <Client/ClientBaseHelpers.h>
#include <Common/DateLUT.h>
#include <Common/DateLUTImpl.h>
#include <Common/LocalDate.h>
#include <Parsers/Lexer.h>
#include <Parsers/ParserQuery.h>
#include <Parsers/parseQuery.h>
#include <Parsers/ASTInsertQuery.h>
#include <Common/StringUtils.h>
#include <Common/UTF8Helpers.h>
#include <Core/Settings.h>
#include <Interpreters/Context.h>
#include <base/find_symbols.h>
#include <Poco/String.h>
#include <string_view>
#if USE_REPLXX
namespace replxx { char const * ansi_color(Replxx::Color); }
#endif
namespace DB
{
namespace Setting
{
extern const SettingsBool implicit_select;
extern const SettingsUInt64 max_parser_depth;
extern const SettingsUInt64 max_parser_backtracks;
}
/// Should we celebrate a bit?
bool isNewYearMode()
{
time_t current_time = time(nullptr);
/// It's bad to be intrusive.
if (current_time % 3 != 0)
return false;
LocalDate now(current_time);
return (now.month() == 12 && now.day() >= 20) || (now.month() == 1 && now.day() <= 5);
}
bool isChineseNewYearMode(const String & local_tz)
{
/// Days of Dec. 20 in Chinese calendar starting from year 2019 to year 2105
static constexpr UInt16 chineseNewYearIndicators[]
= {18275, 18659, 19014, 19368, 19752, 20107, 20491, 20845, 21199, 21583, 21937, 22292, 22676, 23030, 23414, 23768, 24122, 24506,
24860, 25215, 25599, 25954, 26308, 26692, 27046, 27430, 27784, 28138, 28522, 28877, 29232, 29616, 29970, 30354, 30708, 31062,
31446, 31800, 32155, 32539, 32894, 33248, 33632, 33986, 34369, 34724, 35078, 35462, 35817, 36171, 36555, 36909, 37293, 37647,
38002, 38386, 38740, 39095, 39479, 39833, 40187, 40571, 40925, 41309, 41664, 42018, 42402, 42757, 43111, 43495, 43849, 44233,
44587, 44942, 45326, 45680, 46035, 46418, 46772, 47126, 47510, 47865, 48249, 48604, 48958, 49342};
/// All time zone names are acquired from https://www.iana.org/time-zones
static constexpr const char * chineseNewYearTimeZoneIndicators[] = {
/// Time zones celebrating Chinese new year.
"Asia/Shanghai",
"Asia/Chongqing",
"Asia/Harbin",
"Asia/Urumqi",
"Asia/Hong_Kong",
"Asia/Chungking",
"Asia/Macao",
"Asia/Macau",
"Asia/Taipei",
"Asia/Singapore",
/// Time zones celebrating Chinese new year but with different festival names. Let's not print the message for now.
// "Asia/Brunei",
// "Asia/Ho_Chi_Minh",
// "Asia/Hovd",
// "Asia/Jakarta",
// "Asia/Jayapura",
// "Asia/Kashgar",
// "Asia/Kuala_Lumpur",
// "Asia/Kuching",
// "Asia/Makassar",
// "Asia/Pontianak",
// "Asia/Pyongyang",
// "Asia/Saigon",
// "Asia/Seoul",
// "Asia/Ujung_Pandang",
// "Asia/Ulaanbaatar",
// "Asia/Ulan_Bator",
};
static constexpr size_t M = sizeof(chineseNewYearTimeZoneIndicators) / sizeof(chineseNewYearTimeZoneIndicators[0]);
time_t current_time = time(nullptr);
if (chineseNewYearTimeZoneIndicators + M
== std::find_if(chineseNewYearTimeZoneIndicators, chineseNewYearTimeZoneIndicators + M, [&local_tz](const char * tz)
{
return tz == local_tz;
}))
return false;
/// It's bad to be intrusive.
if (current_time % 3 != 0)
return false;
auto days = DateLUT::instance().toDayNum(current_time).toUnderType();
for (auto d : chineseNewYearIndicators)
{
/// Let's celebrate until Lantern Festival
if (d <= days && d + 25 >= days)
return true;
if (d > days)
return false;
}
return false;
}
std::string getChineseZodiac()
{
time_t current_time = time(nullptr);
int year = DateLUT::instance().toYear(current_time);
// Traditional Chinese Zodiac
static constexpr const char * zodiacs[12] = {
"鼠", "牛", "虎", "兔", "龙", "蛇",
"马", "羊", "猴", "鸡", "狗", "猪"
};
//2020 is Rat
int offset = (year - 2020) % 12;
if (offset < 0)
offset += 12;
return zodiacs[offset];
}
#if USE_REPLXX
void highlight(const String & query, std::vector<replxx::Replxx::Color> & colors, const Context & context, int cursor_position)
{
using namespace replxx;
/// The `colors` array maps to a Unicode code point position in a string into a color.
/// A color is set for every position individually (not for a range).
/// Empty input.
if (colors.empty())
return;
/// The colors should be legible (and look gorgeous) in both dark and light themes.
/// When modifying this, check it in both themes.
static const std::unordered_map<Highlight, Replxx::Color> type_to_color =
{
{Highlight::keyword, replxx::color::bold(Replxx::Color::DEFAULT)},
{Highlight::identifier, Replxx::Color::CYAN},
{Highlight::function, Replxx::Color::BROWN},
{Highlight::alias, replxx::color::rgb666(0, 4, 4)},
{Highlight::substitution, Replxx::Color::MAGENTA},
{Highlight::number, replxx::color::rgb666(0, 4, 0)},
{Highlight::string, Replxx::Color::GREEN},
{Highlight::string_like, Replxx::Color::GREEN},
{Highlight::string_regexp, Replxx::Color::GREEN},
};
/// We set reasonably small limits for size/depth, because we don't want the CLI to be slow.
/// While syntax highlighting is unneeded for long queries, which the user couldn't read anyway.
const char * begin = query.data();
const char * end = begin + query.size();
Tokens tokens(begin, end, 10000, true);
IParser::Pos token_iterator(
tokens,
static_cast<uint32_t>(context.getSettingsRef()[Setting::max_parser_depth]),
static_cast<uint32_t>(context.getSettingsRef()[Setting::max_parser_backtracks])
);
Expected expected;
expected.enable_highlighting = true;
/// We don't do highlighting for foreign dialects, such as PRQL and Kusto.
/// Only normal ClickHouse SQL queries are highlighted.
ParserQuery parser(end, false, context.getSettingsRef()[Setting::implicit_select]);
ASTPtr ast;
bool parse_res = false;
try
{
while (!token_iterator->isEnd())
{
parse_res = parser.parse(token_iterator, ast, expected);
if (!parse_res)
break;
if (!token_iterator->isEnd() && token_iterator->type != TokenType::Semicolon)
{
parse_res = false;
break;
}
while (token_iterator->type == TokenType::Semicolon)
++token_iterator;
}
}
catch (...)
{
/// Skip highlighting in the case of exceptions during parsing.
/// It is ok to ignore unknown exceptions here.
return;
}
/// We have to map from byte positions to Unicode positions.
size_t code_point_pos = 0;
const char * char_pos = begin;
for (const auto & range : expected.highlights)
{
const char * metacharacters = "";
if (range.highlight == Highlight::string_like)
metacharacters = "%_";
if (range.highlight == Highlight::string_regexp)
metacharacters = "|()^$.[]?*+{:-";
auto it = type_to_color.find(range.highlight);
if (it != type_to_color.end())
{
while (char_pos < range.begin)
{
++code_point_pos;
char_pos += UTF8::seqLength(*char_pos);
}
int escaped = 0;
while (char_pos < range.end)
{
if (*char_pos == '\\')
{
++escaped;
colors[code_point_pos] = replxx::color::bold(Replxx::Color::LIGHTGRAY);
}
/// The counting of escape characters is quite tricky due to double escaping of string literals + regexps,
/// and the special logic of interpreting escape sequences that are not interpreted by the string literals.
else if ((escaped % 4 == 0 || escaped % 4 == 3) && nullptr != strchr(metacharacters, *char_pos))
{
colors[code_point_pos] = replxx::color::bold(Replxx::Color::BRIGHTMAGENTA);
}
else
{
colors[code_point_pos] = it->second;
escaped = 0;
}
++code_point_pos;
char_pos += UTF8::seqLength(*char_pos);
}
}
}
// Pride flag colors.
static const std::array<Replxx::Color, 8> default_colormap =
{
replxx::color::rgb666(4, 2, 3), // Soft pink
replxx::color::rgb666(4, 1, 1), // Red
replxx::color::rgb666(4, 3, 1), // Gold-orange
replxx::color::rgb666(4, 4, 1), // Yellow
replxx::color::rgb666(1, 4, 1), // Green
replxx::color::rgb666(1, 4, 4), // Teal
replxx::color::rgb666(2, 1, 4), // Indigo
replxx::color::rgb666(4, 1, 4) // Violet
};
static const std::unordered_map<Replxx::Color, Replxx::Color> bright_colormap =
{
{replxx::color::rgb666(4, 2, 3), replxx::color::rgb666(5, 3, 4)}, // Soft pink
{replxx::color::rgb666(4, 1, 1), replxx::color::rgb666(5, 2, 2)}, // Red
{replxx::color::rgb666(4, 3, 1), replxx::color::rgb666(5, 4, 2)}, // Gold-orange
{replxx::color::rgb666(4, 4, 1), replxx::color::rgb666(5, 5, 2)}, // Yellow
{replxx::color::rgb666(1, 4, 1), replxx::color::rgb666(2, 5, 2)}, // Green
{replxx::color::rgb666(1, 4, 4), replxx::color::rgb666(2, 5, 5)}, // Teal
{replxx::color::rgb666(2, 1, 4), replxx::color::rgb666(3, 2, 5)}, // Indigo
{replxx::color::rgb666(4, 1, 4), replxx::color::rgb666(5, 2, 5)} // Violet
};
size_t current_color = 0;
std::vector<Replxx::Color> color_stack;
std::vector<Token> brace_stack;
std::optional<std::tuple<size_t, size_t>> active_matching_brace;
IParser::Pos highlight_token_iterator(
tokens,
static_cast<uint32_t>(context.getSettingsRef()[Setting::max_parser_depth]),
static_cast<uint32_t>(context.getSettingsRef()[Setting::max_parser_backtracks])
);
try
{
while (!highlight_token_iterator->isEnd())
{
if (highlight_token_iterator->isError())
break;
if (highlight_token_iterator->type == TokenType::OpeningRoundBracket)
{
/// On opening round bracket, remember the color we use for it.
color_stack.push_back(default_colormap[current_color % default_colormap.size()]);
brace_stack.push_back(*highlight_token_iterator);
current_color++;
++highlight_token_iterator;
continue;
}
if (highlight_token_iterator->type == TokenType::ClosingRoundBracket)
{
/// Closing round bracket should match the last opening round bracket.
/// If there is no opening round bracket, advance.
if (color_stack.empty() || brace_stack.empty())
{
++highlight_token_iterator;
continue;
}
/// Highlight the closing round bracket.
auto highlight_pos = UTF8::countCodePoints(reinterpret_cast<const UInt8 *>(begin), highlight_token_iterator->begin - begin);
if (highlight_pos < colors.size())
colors[highlight_pos] = color_stack.back();
/// Highlight the matching opening round bracket.
auto matching_brace_pos = UTF8::countCodePoints(reinterpret_cast<const UInt8 *>(begin), brace_stack.back().begin - begin);
if (matching_brace_pos < colors.size())
colors[matching_brace_pos] = color_stack.back();
/// Check if cursor is on the current or matching round brace.
auto mapped_cursor_position = static_cast<uint64_t>(cursor_position);
auto cursor_on_current_brace = mapped_cursor_position == highlight_pos;
auto cursor_on_matching_brace = mapped_cursor_position == matching_brace_pos;
if (cursor_position < 0 || (cursor_on_current_brace || cursor_on_matching_brace))
{
++highlight_token_iterator;
color_stack.pop_back();
brace_stack.pop_back();
continue;
}
/// If the cursor is on one of the round braces,
/// highlight both the opening and closing round braces with a brighter color.
auto bright_color = bright_colormap.at(color_stack.back());
colors[highlight_pos] = bright_color;
colors[matching_brace_pos] = bright_color;
active_matching_brace = std::make_tuple(highlight_pos, matching_brace_pos);
/// Remove the last opening round brace from the stack and advance.
color_stack.pop_back();
brace_stack.pop_back();
++highlight_token_iterator;
continue;
}
++highlight_token_iterator;
while (highlight_token_iterator->type == TokenType::Semicolon)
++highlight_token_iterator;
}
}
catch (...)
{
/// Skip highlighting in the case of exceptions during parsing.
/// It is ok to ignore unknown exceptions here.
return;
}
Token last_token = token_iterator.max();
/// Raw data in INSERT queries, which is not necessarily tokenized.
const char * insert_data = ast ? getInsertData(ast) : nullptr;
/// Highlight the last error in red. If the parser failed or the lexer found an invalid token,
/// or if it didn't parse all the data (except, the data for INSERT query, which is legitimately unparsed)
if ((!parse_res || last_token.isError())
&& !(insert_data && expected.max_parsed_pos >= insert_data)
&& expected.max_parsed_pos >= char_pos)
{
code_point_pos += UTF8::countCodePoints(reinterpret_cast<const UInt8 *>(char_pos), expected.max_parsed_pos - char_pos);
if (code_point_pos >= colors.size())
code_point_pos = colors.size() - 1;
colors[code_point_pos] = Replxx::Color::BRIGHTRED;
if (active_matching_brace)
{
const auto & [highlight_pos, matching_brace_pos] = *active_matching_brace;
const auto opening_brace_pos = UTF8::countCodePoints(reinterpret_cast<const UInt8 *>(begin), highlight_pos);
const auto closing_brace_pos = UTF8::countCodePoints(reinterpret_cast<const UInt8 *>(begin), matching_brace_pos);
/// If the cursor is on one of the round brackets marked as an error,
/// highlight both with a brighter color.
if (code_point_pos == closing_brace_pos || code_point_pos == opening_brace_pos)
{
colors[closing_brace_pos] = replxx::color::rgb666(5, 0, 1);
colors[opening_brace_pos] = replxx::color::rgb666(5, 0, 1);
}
}
}
/// This is a callback for the client/local app to better find query end. Note: this is a kludge, remove it.
if (last_token.type == TokenType::Semicolon || last_token.type == TokenType::VerticalDelimiter
|| query.ends_with(';') || query.ends_with("\\G")) /// This is for raw data in INSERT queries, which is not necessarily tokenized.
{
ReplxxLineReader::setLastIsDelimiter(true);
}
else if (last_token.type != TokenType::Whitespace)
{
ReplxxLineReader::setLastIsDelimiter(false);
}
}
String highlighted(const String & query, const Context & context)
{
// Issue: https://github.com/ClickHouse/ClickHouse/issues/83987
/// Previously utf-8 code points were calculated in the following way:
/// size_t num_code_points = UTF8::countCodePoints(reinterpret_cast<const UInt8 *>(query.data()), query.size());
/// But, `UTF8::countCodePoints` and `UTF8::seqLength` seem to handle invalid UTF-8 sequences inconsistently
/// (e.g., hex literals like x'A0'), causing count mismatches and crashes.
/// For a quick fix, since the highlight function uses `UTF8::seqLength` for iteration, use the same logic for
/// counting to ensure consistency when invalid UTF-8 bytes are detected (use UTF8::countCodePoints for all other
/// cases to mainly for performance concerns).
/// TODO: @bharatnc Fix UTF8::countCodePoints to handle invalid UTF-8 sequences consistently with seqLength so that
/// this logic can be removed.
bool has_invalid_utf8 = false;
for (const char c : query)
{
/// Standalone UTF-8 continuation bytes (0x80-0xBF, e.g. 0xA0 from hex literals)
/// cause countCodePoints/seqLength inconsistency.
if (static_cast<unsigned char>(c) >= 0x80 && static_cast<unsigned char>(c) <= 0xBF)
{
has_invalid_utf8 = true;
break;
}
}
size_t num_code_points;
if (has_invalid_utf8)
{
num_code_points = 0;
const char * pos = query.data();
const char * end = pos + query.size();
while (pos < end)
{
pos += UTF8::seqLength(*pos);
++num_code_points;
}
}
else
num_code_points = UTF8::countCodePoints(reinterpret_cast<const UInt8 *>(query.data()), query.size());
std::vector<replxx::Replxx::Color> colors(num_code_points, replxx::Replxx::Color::DEFAULT);
highlight(query, colors, context, 0);
String res;
size_t query_size = query.size();
res.reserve(query_size * 2);
size_t byte_pos = 0;
size_t code_point_pos = 0;
replxx::Replxx::Color prev_color = replxx::Replxx::Color::DEFAULT;
while (byte_pos < query_size)
{
auto curr_color = colors[code_point_pos];
if (curr_color != prev_color)
{
res += replxx::ansi_color(curr_color);
prev_color = curr_color;
}
size_t code_point_length = UTF8::seqLength(query[byte_pos]);
res.append(query.data() + byte_pos, code_point_length);
byte_pos += code_point_length;
++code_point_pos;
}
if (replxx::Replxx::Color::DEFAULT != prev_color)
res += replxx::ansi_color(replxx::Replxx::Color::DEFAULT);
return res;
}
#endif
void skipSpacesAndComments(const char*& pos, const char* end, std::function<void(std::string_view)> comment_callback)
{
do
{
/// skip spaces to avoid throw exception after last query
while (pos != end && std::isspace(*pos))
++pos;
const char * comment_begin = pos;
/// for skip comment after the last query and to not throw exception
if (end - pos > 2 && *pos == '-' && *(pos + 1) == '-')
{
pos += 2;
/// skip until the end of the line
while (pos != end && *pos != '\n')
++pos;
if (comment_callback)
comment_callback(std::string_view(comment_begin, pos - comment_begin));
}
/// need to parse next sql
else
break;
} while (pos != end);
}
String formatQuery(String query)
{
const unsigned max_parser_depth = DBMS_DEFAULT_MAX_PARSER_DEPTH;
const unsigned max_parser_backtracks = DBMS_DEFAULT_MAX_PARSER_BACKTRACKS;
ParserQuery parser(query.data() + query.size(), /*allow_settings_after_format_in_insert_=*/ false, /*implicit_select_=*/ false);
String res;
res.reserve(query.size());
auto comments_callback = [&](std::string_view comment)
{
res += comment;
res += '\n';
};
const char * begin = query.data();
const char * pos = begin;
const char * end = begin + query.size();
skipSpacesAndComments(pos, end, comments_callback);
size_t queries = 0;
while (pos < end)
{
const char * query_start = pos;
const ASTPtr ast = parseQueryAndMovePosition(parser, pos, end, "query in editor", /*allow_multi_statements=*/ true, /*max_query_size=*/ 0, max_parser_depth, max_parser_backtracks);
std::string_view insert_query_payload;
if (auto * insert_ast = ast->as<ASTInsertQuery>(); insert_ast && insert_ast->data)
{
if (Poco::toLower(insert_ast->format) == "values")
{
/// Reset format to default to have `INSERT INTO table VALUES` instead of `INSERT INTO table VALUES FORMAT Values`
insert_ast->format.clear();
/// We assume that data ends with a newline character (same as in other places)
const char * this_query_end = find_first_symbols<'\n'>(insert_ast->data, end);
insert_ast->end = this_query_end;
pos = this_query_end;
/// Remove semicolon from the INSERT query payload, since it will be added explicitly below
if (*insert_ast->end == '\n')
{
while (insert_ast->end > insert_ast->data && std::isspace(*insert_ast->end))
--insert_ast->end;
}
}
else
pos = insert_ast->end;
/// No need to use getReadBufferFromASTInsertQuery() here, since it does extra things that we do not need here (i.e. handle INFILE)
insert_query_payload = std::string_view(insert_ast->data, insert_ast->end);
}
bool multiline_query = std::string_view(query_start, pos).contains('\n');
if (multiline_query)
res += ast->formatWithSecretsMultiLine();
else
res += ast->formatWithSecretsOneLine();
if (!insert_query_payload.empty())
{
res += ' ';
res += insert_query_payload;
}
bool need_query_delimiter = pos != end || queries > 0;
if (need_query_delimiter)
{
res += ';';
res += '\n';
}
++queries;
skipSpacesAndComments(pos, end, comments_callback);
}
return res;
}
}