forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathASTFunction.cpp
More file actions
1190 lines (1052 loc) · 53.5 KB
/
Copy pathASTFunction.cpp
File metadata and controls
1190 lines (1052 loc) · 53.5 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 <Common/StringUtils.h>
#include <algorithm>
#include <string_view>
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTJSONHelpers.h>
#include <Parsers/ASTJSONReadHelpers.h>
#include <Common/quoteString.h>
#include <Common/FieldVisitorToString.h>
#include <Common/KnownObjectNames.h>
#include <Common/SipHash.h>
#include <IO/Operators.h>
#include <IO/WriteBufferFromString.h>
#include <IO/WriteHelpers.h>
#include <Parsers/ASTAsterisk.h>
#include <Parsers/ASTExpressionList.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTLiteral.h>
#include <Parsers/ASTSelectWithUnionQuery.h>
#include <Parsers/ASTSubquery.h>
#include <Parsers/ASTSetQuery.h>
#include <Parsers/ASTWindowDefinition.h>
#include <Parsers/FunctionSecretArgumentsFinderAST.h>
using namespace std::literals;
namespace DB
{
namespace ErrorCodes
{
extern const int BAD_ARGUMENTS;
extern const int UNEXPECTED_AST_STRUCTURE;
extern const int UNKNOWN_FUNCTION;
}
boost::intrusive_ptr<ASTFunction> makeASTLambda(std::initializer_list<String> param_names, ASTPtr && body)
{
auto tuple = makeASTFunction("tuple");
auto & tuple_args = tuple->arguments->children;
tuple_args.reserve(param_names.size());
for (const auto & param_name : param_names)
tuple_args.emplace_back(make_intrusive<ASTIdentifier>(param_name));
return makeASTFunction("lambda", std::move(tuple), std::move(body));
}
void ASTFunction::setNoEmptyArgs(bool value)
{
flags<ASTFunctionFlags>().no_empty_args = value;
/// Also clear the empty arguments node to keep formatting round-trip consistent:
/// `MergeTree()` with noEmptyArgs formats as `MergeTree`, which re-parses without arguments.
if (value && arguments && arguments->children.empty())
{
children.erase(std::remove(children.begin(), children.end(), arguments), children.end());
arguments.reset();
}
}
void ASTFunction::appendColumnNameImpl(WriteBuffer & ostr) const
{
/// These functions contain some unexpected ASTs in arguments (e.g. SETTINGS or even a SELECT query)
if (name == "view" || name == "viewIfPermitted" || name == "mysql" || name == "postgresql" || name == "mongodb" || name == "s3")
throw Exception(ErrorCodes::UNKNOWN_FUNCTION, "Table function '{}' cannot be used as an expression", name);
/// If function can be converted to literal it will be parsed as literal after formatting.
/// In distributed query it may lead to mismatched column names.
/// To avoid it we check whether we can convert function to literal.
if (auto literal = toLiteral())
{
literal->appendColumnName(ostr);
return;
}
writeString(name, ostr);
if (parameters)
{
writeChar('(', ostr);
for (auto it = parameters->children.begin(); it != parameters->children.end(); ++it)
{
if (it != parameters->children.begin())
writeCString(", ", ostr);
(*it)->appendColumnName(ostr);
}
writeChar(')', ostr);
}
writeChar('(', ostr);
if (arguments)
{
for (auto it = arguments->children.begin(); it != arguments->children.end(); ++it)
{
if (it != arguments->children.begin())
writeCString(", ", ostr);
(*it)->appendColumnName(ostr);
}
}
writeChar(')', ostr);
if (getNullsAction() == NullsAction::RESPECT_NULLS)
writeCString(" RESPECT NULLS", ostr);
else if (getNullsAction() == NullsAction::IGNORE_NULLS)
writeCString(" IGNORE NULLS", ostr);
if (isWindowFunction())
{
writeCString(" OVER ", ostr);
if (!window_name.empty())
{
ostr << window_name;
}
else
{
FormatSettings format_settings{true /* one_line */};
FormatState state;
FormatStateStacked frame;
writeCString("(", ostr);
window_definition->format(ostr, format_settings, state, frame);
writeCString(")", ostr);
}
}
}
void ASTFunction::writeJSON(WriteBuffer & out) const
{
JSONObjectWriter w(out, "Function");
w.writeString("name", name);
w.writeChild("arguments", arguments);
w.writeChild("parameters", parameters);
if (!window_name.empty())
w.writeString("window_name", window_name);
w.writeChild("window_definition", window_definition);
if (isOperator())
w.writeBool("is_operator", true);
if (isWindowFunction())
w.writeBool("is_window_function", true);
if (computeAfterWindowFunctions())
w.writeBool("compute_after_window_functions", true);
if (isLambdaFunction())
w.writeBool("is_lambda_function", true);
if (preferSubqueryToFunctionFormatting())
w.writeBool("prefer_subquery_to_function_formatting", true);
if (noEmptyArgs())
w.writeBool("no_empty_args", true);
if (isCompoundName())
w.writeBool("is_compound_name", true);
if (getNullsAction() == NullsAction::RESPECT_NULLS)
w.writeString("nulls_action", "RESPECT_NULLS");
else if (getNullsAction() == NullsAction::IGNORE_NULLS)
w.writeString("nulls_action", "IGNORE_NULLS");
if (getKind() != Kind::ORDINARY_FUNCTION)
{
const char * kind_str = nullptr;
switch (getKind())
{
case Kind::WINDOW_FUNCTION: kind_str = "WINDOW_FUNCTION"; break;
case Kind::LAMBDA_FUNCTION: kind_str = "LAMBDA_FUNCTION"; break;
case Kind::TABLE_ENGINE: kind_str = "TABLE_ENGINE"; break;
case Kind::DATABASE_ENGINE: kind_str = "DATABASE_ENGINE"; break;
case Kind::BACKUP_NAME: kind_str = "BACKUP_NAME"; break;
case Kind::CODEC: kind_str = "CODEC"; break;
case Kind::STATISTICS: kind_str = "STATISTICS"; break;
default: break;
}
if (kind_str)
w.writeString("kind", kind_str);
}
w.writeAlias(*this);
}
void ASTFunction::readJSON(const Poco::JSON::Object & json)
{
JSONObjectReader r(json);
name = r.getString("name");
if (name.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Empty 'name' for ASTFunction");
setIsOperator(r.getBool("is_operator"));
setIsWindowFunction(r.getBool("is_window_function"));
setComputeAfterWindowFunctions(r.getBool("compute_after_window_functions"));
setIsLambdaFunction(r.getBool("is_lambda_function"));
setPreferSubqueryToFunctionFormatting(r.getBool("prefer_subquery_to_function_formatting"));
setNoEmptyArgs(r.getBool("no_empty_args"));
setIsCompoundName(r.getBool("is_compound_name"));
String nulls_action_str = r.getString("nulls_action");
if (nulls_action_str == "RESPECT_NULLS")
setNullsAction(NullsAction::RESPECT_NULLS);
else if (nulls_action_str == "IGNORE_NULLS")
setNullsAction(NullsAction::IGNORE_NULLS);
else if (!nulls_action_str.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unknown 'nulls_action' value '{}' during AST JSON deserialization", nulls_action_str);
String kind_str = r.getString("kind");
if (kind_str == "WINDOW_FUNCTION")
setKind(Kind::WINDOW_FUNCTION);
else if (kind_str == "LAMBDA_FUNCTION")
setKind(Kind::LAMBDA_FUNCTION);
else if (kind_str == "TABLE_ENGINE")
setKind(Kind::TABLE_ENGINE);
else if (kind_str == "DATABASE_ENGINE")
setKind(Kind::DATABASE_ENGINE);
else if (kind_str == "BACKUP_NAME")
setKind(Kind::BACKUP_NAME);
else if (kind_str == "CODEC")
setKind(Kind::CODEC);
else if (kind_str == "STATISTICS")
setKind(Kind::STATISTICS);
else if (!kind_str.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unknown 'kind' value '{}' during AST JSON deserialization", kind_str);
/// `arguments` and `parameters` are parser-produced `ASTExpressionList` children. The formatter
/// iterates their `children`, so a scalar node here would silently rewrite the function (e.g.
/// `f(x)` becoming `f()`). Reject any other node type at the JSON boundary with `BAD_ARGUMENTS`.
arguments = r.readChildOfType<ASTExpressionList>("arguments");
if (arguments)
children.push_back(arguments);
parameters = r.readChildOfType<ASTExpressionList>("parameters");
if (parameters)
children.push_back(parameters);
window_name = r.getString("window_name");
/// `window_definition` is parser-produced as an `ASTWindowDefinition`; `finishFormatWithWindow`
/// prints it inside `OVER (...)` and `QueryTreeBuilder::buildWindow` does
/// `window_definition->as<const ASTWindowDefinition &>()`. Reject any other node type from
/// malformed `clickhouse_json` here instead of reaching that downstream cast.
window_definition = r.readChildOfType<ASTWindowDefinition>("window_definition");
if (window_definition)
children.push_back(window_definition);
/// A window payload or window kind is only formatted when the function is a window function.
/// Accepting such input while 'is_window_function' is false would silently drop the OVER (...) clause,
/// producing an AST the parser cannot have produced.
if ((r.has("window_name") || window_definition || getKind() == Kind::WINDOW_FUNCTION) && !isWindowFunction())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"'window_name', 'window_definition' or 'kind' = 'WINDOW_FUNCTION' require 'is_window_function' to be true during AST JSON deserialization");
/// The parser only assigns `kind = LAMBDA_FUNCTION` together with `is_lambda_function`
/// (`makeASTFunction` for the lambda operator). Reject a `clickhouse_json` payload that marks a
/// function as the lambda kind without the flag, which the parser could not have produced.
/// Note the reverse does not hold: `APPLY (x -> ...)` sets `is_lambda_function` while leaving
/// `kind` ordinary, so only this single direction is a parser invariant.
if (getKind() == Kind::LAMBDA_FUNCTION && !isLambdaFunction())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"'kind' = 'LAMBDA_FUNCTION' requires 'is_lambda_function' to be true during AST JSON deserialization");
if (isWindowFunction() && window_name.empty() && !window_definition)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Window function requires either a non-empty 'window_name' or a 'window_definition' child during AST JSON deserialization");
/// The parser produces a bare `SelectWithUnionQuery` function argument only inside the table
/// functions `view` and `viewIfPermitted` (`ViewLayer` is their only producer): `view(SELECT ...)`
/// has exactly one argument, the select, and `viewIfPermitted(SELECT ... ELSE table_function(...))`
/// has exactly (select, function), because after `ELSE` only a function call is accepted; neither
/// form has parameters. In an expression context both names parse as ordinary functions and a bare
/// select cannot appear among their arguments at all. The formatter prints special forms for
/// exactly the table function shapes (the query-argument form, which silently drops parameters,
/// and the `ELSE` form, which is unparseable elsewhere), so reject any other combination that
/// contains a bare select, which the parser cannot produce. The checks are case-insensitive
/// because the parser dispatches to the table function parser on the lowercased name, so any
/// spelling hits the same parse-back constraints.
bool is_view = equalsCaseInsensitive(name, "view");
bool is_view_if_permitted = equalsCaseInsensitive(name, "viewIfPermitted");
if ((is_view || is_view_if_permitted) && arguments)
{
bool has_bare_select = std::ranges::any_of(
arguments->children, [](const ASTPtr & child) { return child->as<ASTSelectWithUnionQuery>() != nullptr; });
bool is_table_function_shape = !parameters
&& (is_view
? arguments->children.size() == 1 && arguments->children[0]->as<ASTSelectWithUnionQuery>()
: arguments->children.size() == 2 && arguments->children[0]->as<ASTSelectWithUnionQuery>()
&& arguments->children[1]->as<ASTFunction>());
if (has_bare_select && !is_table_function_shape)
{
if (is_view)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"'view' with a select query argument must have exactly one argument, a select query, "
"and no parameters during AST JSON deserialization");
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"'viewIfPermitted' with a select query argument must have exactly two arguments, a select query "
"followed by a function, and no parameters during AST JSON deserialization");
}
/// For the table function form the parser emits only the canonical spelling (`ViewLayer`
/// dispatches on the lowercased name but always produces `view` or `viewIfPermitted`), and
/// execution matches the name case-sensitively (e.g. `StorageView::replaceWithSubquery` and
/// the table function factory), so a non-canonical spelling that reaches the interpreter
/// through `clickhouse_json` would fail. Canonicalize it the way the parser does.
if (is_table_function_shape)
name = is_view ? "view" : "viewIfPermitted";
}
r.readAlias(*this);
}
void ASTFunction::finishFormatWithWindow(WriteBuffer & ostr, const FormatSettings & settings, FormatState & state, FormatStateStacked frame) const
{
if (getNullsAction() == NullsAction::RESPECT_NULLS)
ostr << " RESPECT NULLS";
else if (getNullsAction() == NullsAction::IGNORE_NULLS)
ostr << " IGNORE NULLS";
if (!isWindowFunction())
return;
ostr << " OVER ";
if (!window_name.empty())
{
ostr << backQuoteIfNeed(window_name);
}
else
{
ostr << "(";
window_definition->format(ostr, settings, state, frame);
ostr << ")";
}
}
/** Get the text that identifies this element. */
String ASTFunction::getID(char delim) const
{
return "Function" + (delim + name);
}
ASTPtr ASTFunction::clone() const
{
auto res = make_intrusive<ASTFunction>(*this);
res->children.clear();
if (arguments) { res->arguments = arguments->clone(); res->children.push_back(res->arguments); }
if (parameters) { res->parameters = parameters->clone(); res->children.push_back(res->parameters); }
if (window_definition)
{
res->window_definition = window_definition->clone();
res->children.push_back(res->window_definition);
}
return res;
}
void ASTFunction::updateTreeHashImpl(SipHash & hash_state, bool ignore_aliases) const
{
hash_state.update(name.size());
hash_state.update(name);
ASTWithAlias::updateTreeHashImpl(hash_state, ignore_aliases);
hash_state.update(getNullsAction());
if (isWindowFunction())
{
hash_state.update(window_name.size());
hash_state.update(window_name);
if (window_definition)
window_definition->updateTreeHashImpl(hash_state, ignore_aliases);
}
}
template <typename Container>
static ASTPtr createLiteral(const ASTs & arguments)
{
Container container;
for (const auto & arg : arguments)
{
if (const auto * literal = arg->as<ASTLiteral>())
{
container.push_back(literal->value);
}
else if (auto * func = arg->as<ASTFunction>())
{
if (auto func_literal = func->toLiteral())
container.push_back(func_literal->as<ASTLiteral>()->value);
else
return {};
}
else
/// Some of the Array or Tuple arguments is not literal
return {};
}
return make_intrusive<ASTLiteral>(container);
}
ASTPtr ASTFunction::toLiteral() const
{
if (!arguments)
return {};
if (name == "array")
return createLiteral<Array>(arguments->children);
if (name == "tuple")
return createLiteral<Tuple>(arguments->children);
return {};
}
ASTSelectWithUnionQuery * ASTFunction::tryGetQueryArgument() const
{
if (arguments && arguments->children.size() == 1)
{
return arguments->children[0]->as<ASTSelectWithUnionQuery>();
}
return nullptr;
}
/// Whether a nested secret map child is a `key = value` argument whose value stays visible when the
/// map is masked (the non-secret identifiers of `extra_credentials`; `headers` values are all hidden).
static bool isNonSecretMapChild(const String & map_name, const IAST * arg)
{
if (map_name != "extra_credentials")
return false;
const auto * equals_func = arg->as<ASTFunction>();
if (!equals_func || equals_func->name != "equals" || !equals_func->arguments || equals_func->arguments->children.size() != 2)
return false;
/// Keep the value visible only when it is a plain literal or identifier; a non-literal value (e.g.
/// `role_arn = headers('Authorization' = '...')`) can hide a nested secret and is formatted verbatim
/// before the parser rejects it, so fail closed.
const auto & value_ast = equals_func->arguments->children[1];
if (!value_ast->as<ASTLiteral>() && !value_ast->as<ASTIdentifier>())
return false;
const auto & key_ast = equals_func->arguments->children[0];
if (const auto * key_literal = key_ast->as<ASTLiteral>())
return key_literal->value.getType() == Field::Types::String
&& FunctionSecretArgumentsFinder::isNonSecretExtraCredentialsKey(key_literal->value.safeGet<String>());
if (const auto * key_identifier = key_ast->as<ASTIdentifier>())
return FunctionSecretArgumentsFinder::isNonSecretExtraCredentialsKey(key_identifier->name());
return false;
}
static bool formatNamedArgWithHiddenValue(IAST * arg, WriteBuffer & ostr, const IAST::FormatSettings & settings, IAST::FormatState & state, IAST::FormatStateStacked frame)
{
const auto * equals_func = arg->as<ASTFunction>();
if (!equals_func || (equals_func->name != "equals"))
return false;
const auto * expr_list = equals_func->arguments->as<ASTExpressionList>();
if (!expr_list)
return false;
const auto & equal_args = expr_list->children;
if (equal_args.size() != 2)
return false;
equal_args[0]->format(ostr, settings, state, frame);
ostr << " = ";
ostr << "'[HIDDEN]'";
return true;
}
/// Only some types of arguments are accepted by the parser of the '->' operator.
static bool isAcceptableArgumentsForLambdaExpression(const ASTs & arguments)
{
if (arguments.size() == 2)
{
const auto & first_argument = arguments[0];
if (first_argument->as<ASTIdentifier>())
return true;
const ASTFunction * first_argument_function = first_argument->as<ASTFunction>();
if (first_argument_function && (first_argument_function->name == "tuple") && first_argument_function->arguments)
{
const auto & tuple_args = first_argument_function->arguments->children;
auto all_tuple_arguments_are_identifiers
= std::all_of(tuple_args.begin(), tuple_args.end(), [](const ASTPtr & x) { return x->as<ASTIdentifier>(); });
if (all_tuple_arguments_are_identifiers)
return true;
}
}
return false;
}
namespace
{
struct FunctionOperatorMapping
{
std::string_view function_name;
std::string_view operator_name;
};
}
void ASTFunction::formatImplWithoutAlias(WriteBuffer & ostr, const FormatSettings & settings, FormatState & state, FormatStateStacked frame) const
{
frame.expression_list_prepend_whitespace = false;
auto kind = getKind();
if (kind == Kind::CODEC || kind == Kind::STATISTICS || kind == Kind::BACKUP_NAME)
frame.allow_operators = false;
FormatStateStacked nested_need_parens = frame;
FormatStateStacked nested_dont_need_parens = frame;
nested_need_parens.need_parens = true;
nested_dont_need_parens.need_parens = false;
/// `list_element_index` describes the node's position among the direct elements of the
/// enclosing expression list and is only meaningful one level deep. Operands reached
/// through an operator (tupleElement, arrayElement, etc.) are not list elements, so reset
/// it here; the argument-list loops below re-set it explicitly per argument when needed.
nested_need_parens.list_element_index = 0;
nested_dont_need_parens.list_element_index = 0;
if (auto * query = tryGetQueryArgument())
{
std::string nl_or_nothing = settings.one_line ? "" : "\n";
std::string indent_str = settings.one_line ? "" : std::string(4u * frame.indent, ' ');
if (!name.empty())
ostr << backQuoteIfNeed(name);
ostr << "(";
ostr << nl_or_nothing;
FormatStateStacked frame_nested = frame;
frame_nested.need_parens = false;
frame_nested.parent_has_trailing_settings = false;
++frame_nested.indent;
query->format(ostr, settings, state, frame_nested);
ostr << nl_or_nothing << indent_str;
ostr << ")";
return;
}
/// The `ELSE` form exists only for the table function `viewIfPermitted(SELECT ... ELSE table_function(...))`,
/// whose arguments are always a bare select query and a function call (`ViewLayer` in the parser).
/// In an expression context `viewIfPermitted` parses as an ordinary function (e.g. `viewIfPermitted(1, 2)`),
/// and formatting it with `ELSE` would produce text that cannot be parsed back
/// (inconsistent AST formatting, an exception in debug builds), so such shapes take the generic path below.
/// The name check is case-insensitive: the parser dispatches to the table function parser on the
/// lowercased name, so a non-canonical spelling (producible only through AST JSON deserialization)
/// with this shape must also be printed in the `ELSE` form to stay parseable.
if (arguments && !parameters && arguments->children.size() == 2 && equalsCaseInsensitive(name, "viewIfPermitted")
&& arguments->children[0]->as<ASTSelectWithUnionQuery>() && arguments->children[1]->as<ASTFunction>())
{
/// viewIfPermitted() needs special formatting: ELSE instead of comma between arguments, and better indents too.
const auto * nl_or_nothing = settings.one_line ? "" : "\n";
auto indent0 = settings.one_line ? "" : String(4u * frame.indent, ' ');
auto indent1 = settings.one_line ? "" : String(4u * (frame.indent + 1), ' ');
auto indent2 = settings.one_line ? "" : String(4u * (frame.indent + 2), ' ');
ostr << name << "(" << nl_or_nothing;
FormatStateStacked frame_nested = frame;
frame_nested.need_parens = false;
frame_nested.parent_has_trailing_settings = false;
frame_nested.indent += 2;
arguments->children[0]->format(ostr, settings, state, frame_nested);
ostr << nl_or_nothing << indent1 << (settings.one_line ? " " : "")
<< "ELSE " << nl_or_nothing << indent2;
/// The parser accepts only a function call after ELSE (it is a table function such as null('structure')),
/// so a function that would normally be formatted as an operator (e.g. `not`) must keep
/// the function-call form here, or the query could not be parsed back.
FormatStateStacked frame_else = frame_nested;
frame_else.allow_operators = false;
arguments->children[1]->format(ostr, settings, state, frame_else);
ostr << nl_or_nothing << indent0 << ")";
return;
}
/// Should this function to be written as operator?
bool written = false;
if (isOperator() && arguments && !parameters && frame.allow_operators && getNullsAction() == NullsAction::EMPTY)
{
/// Unary prefix operators.
if (arguments->children.size() == 1)
{
static constexpr std::array<FunctionOperatorMapping, 2> operators = {{
{"negate", "-"},
{"not", "NOT "},
}};
if (auto it = std::ranges::find_if(operators, [&](const auto & op) { return equalsCaseInsensitive(name, op.function_name); });
it != operators.end())
{
const auto & func_symbol = it->operator_name;
const auto * literal = arguments->children[0]->as<ASTLiteral>();
const auto * function = arguments->children[0]->as<ASTFunction>();
const auto * subquery = arguments->children[0]->as<ASTSubquery>();
bool is_tuple = (literal && literal->value.getType() == Field::Types::Tuple)
|| (function && function->name == "tuple" && function->arguments && function->arguments->children.size() > 1);
bool is_array = (literal && literal->value.getType() == Field::Types::Array)
|| (function && function->name == "array");
bool has_alias = !arguments->children[0]->tryGetAlias().empty();
/// Do not add parentheses for tuple and array literal, otherwise extra parens will be added `-((3, 7, 3), 1)` -> `-(((3, 7, 3), 1))`, `-[1]` -> `-([1])`
bool literal_need_parens = literal && !is_tuple && !is_array;
/// Negate always requires parentheses, otherwise -(-1) will be printed as --1
/// Also extra parentheses are needed for subqueries with NOT, because NOT (SELECT 1) is ambiguous.
/// Note: Tuples no longer need inside_parens for NOT because NOT is now always parsed as a
/// unary prefix operator (not a function call), so NOT (1, 2, 3) correctly produces NOT(tuple(1,2,3)).
/// Note: If the arg to negate/not/- has an alias, we never need the inside parens
bool inside_parens = !has_alias
&& ((name == "negate" && (literal_need_parens || (function && function->name == "negate")))
|| (subquery && name == "not"));
/// We DO need parentheses around a single literal
/// For example, SELECT (NOT 0) + (NOT 0) cannot be transformed into SELECT NOT 0 + NOT 0, since
/// this is equal to SELECT NOT (0 + NOT 0)
/// Only negate (-) can safely move before parentheses: -(x + y) is unambiguous.
/// NOT cannot: NOT (subquery) NOT LIKE x would be parsed as NOT ((subquery) NOT LIKE x),
/// because boolean NOT has lower precedence than comparison operators.
bool can_move_before_parens = frame.allow_moving_operators_before_parens && (name == "negate");
bool outside_parens = frame.need_parens && (!can_move_before_parens || !inside_parens);
/// Do not add extra parentheses for functions inside negate, i.e. -(-toUInt64(-(1)))
if (inside_parens)
nested_need_parens.need_parens = false;
if (outside_parens)
ostr << '(';
ostr << func_symbol;
if (inside_parens)
{
ostr << '(';
/// We have just emitted `(` around the single argument, so suppress the
/// argument's own `parenthesized` parens (which would otherwise duplicate ours).
/// We bypass ASTExpressionList::format here to ensure the flag reaches the
/// argument node directly (the flag is consumed at the first IAST::format call).
FormatStateStacked inner_frame = nested_need_parens;
inner_frame.wrapped_in_parens = true;
arguments->children[0]->format(ostr, settings, state, inner_frame);
ostr << ')';
}
else
{
arguments->format(ostr, settings, state, nested_need_parens);
}
written = true;
if (outside_parens)
ostr << ')';
}
}
/// Unary postfix operators.
if (!written && arguments->children.size() == 1)
{
static constexpr std::array<FunctionOperatorMapping, 2> operators = {{
{"isNull", " IS NULL"},
{"isNotNull", " IS NOT NULL"},
}};
if (auto it = std::ranges::find_if(operators, [&](const auto & op) { return equalsCaseInsensitive(name, op.function_name); });
it != operators.end())
{
if (frame.need_parens)
ostr << '(';
arguments->format(ostr, settings, state, nested_need_parens);
ostr << it->operator_name;
if (frame.need_parens)
ostr << ')';
written = true;
}
}
/** need_parens - do we need parentheses around the expression with the operator.
* They are needed only if this expression is included in another expression with the operator.
*/
bool is_like_with_escape = false;
if (arguments->children.size() == 3
&& (name == "like" || name == "ilike" || name == "notLike" || name == "notILike"))
{
if (const auto * escape_literal = arguments->children[2]->as<ASTLiteral>())
is_like_with_escape = escape_literal->value.getType() == Field::Types::String;
}
if (!written && (arguments->children.size() == 2 || is_like_with_escape))
{
static constexpr std::array<FunctionOperatorMapping, 21> operators =
{{
{"multiply", " * "},
{"divide", " / "},
{"modulo", " % "},
{"plus", " + "},
{"minus", " - "},
{"notEquals", " != "},
{"lessOrEquals", " <= "},
{"greaterOrEquals", " >= "},
{"less", " < "},
{"greater", " > "},
{"equals", " = "},
{"isNotDistinctFrom", " <=> "},
{"isDistinctFrom", " IS DISTINCT FROM "},
{"like", " LIKE "},
{"ilike", " ILIKE "},
{"notLike", " NOT LIKE "},
{"notILike", " NOT ILIKE "},
{"in", " IN "},
{"notIn", " NOT IN "},
{"globalIn", " GLOBAL IN "},
{"globalNotIn", " GLOBAL NOT IN "}
}};
if (auto it = std::ranges::find(operators, name, &FunctionOperatorMapping::function_name); it != operators.end())
{
/// IN operators need extra parentheses to avoid parsing ambiguity when used as function arguments.
/// The parser cannot handle IN inside multi-argument function calls without parentheses.
/// Example: position(1 IN (SELECT 1), 2) must be formatted as position((1 IN (SELECT 1)), 2)
bool is_in_operator = (name == "in" || name == "notIn" || name == "globalIn" || name == "globalNotIn");
bool in_function_args = frame.current_function != nullptr;
bool need_parens_around_in = frame.need_parens || (is_in_operator && in_function_args);
if (need_parens_around_in)
ostr << '(';
/// Our wrapping `(...)` (either from need_parens_around_in here, or from the
/// `parenthesized` flag handled in IAST::format) already isolates this IN from
/// the enclosing function-argument list, so descendants must not add another
/// layer of parens for the same reason. Clear `current_function` for the
/// children so a nested IN sees `in_function_args == false`. Without this, a
/// query like `f(1, 2 IN ((3 IN (4, 5)) AS x))` formats as
/// `f(1, (2 IN ((3 IN (4, 5)) AS x)))`, the re-parse sets `parenthesized=true`
/// on the outer IN (so `IAST::format` emits the outer parens and resets
/// `current_function`), and the second format drops the inner `(3 IN (4, 5))`,
/// breaking the format-parse-format round-trip check.
if (need_parens_around_in)
{
nested_need_parens.current_function = nullptr;
nested_dont_need_parens.current_function = nullptr;
}
arguments->children[0]->format(ostr, settings, state, nested_need_parens);
ostr << it->operator_name;
/// Format `x IN 1` as `x IN (1)`: put parens around the right-hand side even if
/// there is a single element in the set (some external databases the query can be
/// forwarded to require them). Self-grouping forms — subqueries, function calls,
/// tuple and array literals — emit their own brackets; an aliased right-hand side
/// is wrapped in parens by the generic aliased-expression handling.
const auto * second_arg_func = arguments->children[1]->as<ASTFunction>();
const auto * second_arg_literal = arguments->children[1]->as<ASTLiteral>();
bool is_literal_tuple_or_array = second_arg_literal
&& (second_arg_literal->value.getType() == Field::Types::Tuple
|| second_arg_literal->value.getType() == Field::Types::Array);
bool extra_parens_around_in_rhs = is_in_operator
&& !arguments->children[1]->as<ASTSubquery>() && !second_arg_func && !is_literal_tuple_or_array
&& arguments->children[1]->tryGetAlias().empty();
if (extra_parens_around_in_rhs)
{
ostr << '(';
/// We have just emitted `(` around the right-hand side, so suppress the
/// child's own `parenthesized` parens (which would otherwise duplicate ours).
FormatStateStacked inner_frame = nested_dont_need_parens;
inner_frame.wrapped_in_parens = true;
arguments->children[1]->format(ostr, settings, state, inner_frame);
ostr << ')';
}
else
arguments->children[1]->format(ostr, settings, state, nested_need_parens);
/// LIKE/ILIKE with ESCAPE clause: format the 3rd argument as ESCAPE 'char'
if (is_like_with_escape)
{
ostr << " ESCAPE ";
arguments->children[2]->format(ostr, settings, state, nested_dont_need_parens);
}
if (need_parens_around_in)
ostr << ')';
written = true;
}
if (!written && name == "arrayElement"sv)
{
if (frame.need_parens)
ostr << '(';
/// Don't allow moving operators like '-' before parens,
/// otherwise (-(42))[3] will be formatted as -(42)[3] that will be parsed as -(42[3]);
nested_need_parens.allow_moving_operators_before_parens = false;
arguments->children[0]->format(ostr, settings, state, nested_need_parens);
ostr << '[';
arguments->children[1]->format(ostr, settings, state, nested_dont_need_parens);
ostr << ']';
written = true;
if (frame.need_parens)
ostr << ')';
}
if (!written && name == "tupleElement"sv && arguments->children.size() == 2)
{
// fuzzer sometimes may insert tupleElement() created from ASTLiteral:
//
// Function_tupleElement, 0xx
// -ExpressionList_, 0xx
// --Literal_Int64_255, 0xx
// --Literal_Int64_100, 0xx
//
// And in this case it will be printed as "255.100", which
// later will be parsed as float, and formatting will be
// inconsistent.
//
// So instead of printing it as regular tuple,
// let's print it as ExpressionList instead (i.e. with ", " delimiter).
//
// Only use dot-syntax for 2-argument tupleElement (expr.field).
// The 3-argument form tupleElement(expr, field, default) cannot use
// dot-syntax because the default value would be lost during formatting.
bool tuple_arguments_valid = true;
const auto * lit_left = arguments->children[0]->as<ASTLiteral>();
const auto * lit_right = arguments->children[1]->as<ASTLiteral>();
if (arguments->children[0]->as<ASTAsterisk>())
tuple_arguments_valid = false;
if (lit_left)
{
Field::Types::Which type = lit_left->value.getType();
if (type != Field::Types::Tuple && type != Field::Types::Array)
{
tuple_arguments_valid = false;
}
}
/// It can be printed in a form of 'x.1' only if right hand side
/// is an unsigned integer lineral. We also allow nonnegative
/// signed integer literals, because the fuzzer sometimes inserts
/// them, and we want to have consistent formatting.
if (tuple_arguments_valid && lit_right)
{
if (isInt64OrUInt64FieldType(lit_right->value.getType())
&& lit_right->value.safeGet<Int64>() >= 0)
{
if (frame.need_parens)
ostr << '(';
/// Little hack: Expression like this: (tab.*).1 (tab contains single tuple column)
/// causes inconsistent formatting because it is formatted as tab.*.1 which is invalid.
/// So when child 0 has more than one element, we surround it with parens.
/// Exception: array and tuple functions format with their own brackets ([...] and (...)),
/// which are already unambiguous with .N syntax. Adding extra parens around them
/// would cause inconsistent formatting when re-parsed, because the parser's fast path
/// creates ASTLiteral (size=1, no parens) while ASTFunction has size>1.
const auto * left_func = arguments->children[0]->as<ASTFunction>();
bool left_needs_parens = arguments->children[0]->size() > 1
&& !(left_func && (left_func->name == "array" || left_func->name == "tuple"));
if (left_needs_parens)
{
nested_need_parens.need_parens = false; /// Don't want duplicate parens
/// We have just emitted `(` around the child, so suppress the
/// child's own `parenthesized` parens (which would otherwise duplicate ours).
nested_need_parens.wrapped_in_parens = true;
ostr << '(';
}
/// Don't allow moving operators like '-' before parens,
/// otherwise (-(42)).1 will be formatted as -(42).1 that will be parsed as -((42).1)
nested_need_parens.allow_moving_operators_before_parens = false;
arguments->children[0]->format(ostr, settings, state, nested_need_parens);
if (left_needs_parens)
ostr << ')';
ostr << ".";
arguments->children[1]->format(ostr, settings, state, nested_dont_need_parens);
written = true;
if (frame.need_parens)
ostr << ')';
}
}
}
/// Only some types of arguments are accepted by the parser of the '->' operator.
if (!written && name == "lambda"sv && isAcceptableArgumentsForLambdaExpression(arguments->children))
{
const auto & first_argument = arguments->children[0];
const ASTFunction * first_argument_function = first_argument->as<ASTFunction>();
bool first_argument_is_tuple = first_argument_function && first_argument_function->name == "tuple";
/// Special case: zero elements tuple in lhs of lambda is printed as ().
/// Special case: one-element tuple in lhs of lambda is printed as its element.
/// If lambda function is not the first element in the list, it has to be put in parentheses.
/// Example: f(x, (y -> z)) should not be printed as f((x, y) -> z).
if (frame.need_parens || frame.list_element_index > 0)
ostr << '(';
if (first_argument_is_tuple
&& first_argument_function->arguments
&& (first_argument_function->arguments->children.size() == 1 || first_argument_function->arguments->children.empty()))
{
if (first_argument_function->arguments->children.size() == 1)
first_argument_function->arguments->children[0]->format(ostr, settings, state, nested_need_parens);
else
ostr << "()";
}
else
first_argument->format(ostr, settings, state, nested_need_parens);
ostr << " -> ";
arguments->children[1]->format(ostr, settings, state, nested_need_parens);
if (frame.need_parens || frame.list_element_index > 0)
ostr << ')';
written = true;
}
}
if (!written && arguments->children.size() >= 2)
{
constexpr std::array<FunctionOperatorMapping, 2> operators
{{
{"and", " AND "},
{"or", " OR "}
}};
if (auto it = std::ranges::find(operators, name, &FunctionOperatorMapping::function_name); it != operators.end())
{
if (frame.need_parens)
ostr << '(';
for (size_t i = 0; i < arguments->children.size(); ++i)
{
if (i != 0)
ostr << it->operator_name;
if (arguments->children[i]->as<ASTSetQuery>())
ostr << "SETTINGS ";
arguments->children[i]->format(ostr, settings, state, nested_need_parens);
}
if (frame.need_parens)
ostr << ')';
written = true;
}
}
if (!written && name == "array"sv && isOperator())
{
ostr << '[';
for (size_t i = 0; i < arguments->children.size(); ++i)
{
if (i != 0)
ostr << ", ";
if (arguments->children[i]->as<ASTSetQuery>())
ostr << "SETTINGS ";
nested_dont_need_parens.list_element_index = i;
arguments->children[i]->format(ostr, settings, state, nested_dont_need_parens);
}
ostr << ']';
written = true;
}
/// Note: `frame.need_parens` cannot be set here together with a non-empty alias:
/// the generic aliased-expression handling consumes it (emitting the wrapping parens)
/// before calling `formatImplWithoutAlias`.
if (!written && arguments->children.size() >= 2 && name == "tuple"sv && isOperator())
{
ostr << '(';
for (size_t i = 0; i < arguments->children.size(); ++i)
{
if (i != 0)
ostr << ", ";
if (arguments->children[i]->as<ASTSetQuery>())
ostr << "SETTINGS ";
nested_dont_need_parens.list_element_index = i;
arguments->children[i]->format(ostr, settings, state, nested_dont_need_parens);
}
ostr << ')';
written = true;
}
if (!written && name == "map"sv)
{
ostr << "map(";
for (size_t i = 0; i < arguments->children.size(); ++i)
{
if (i != 0)
ostr << ", ";
if (arguments->children[i]->as<ASTSetQuery>())
ostr << "SETTINGS ";
nested_dont_need_parens.list_element_index = i;
arguments->children[i]->format(ostr, settings, state, nested_dont_need_parens);
}
ostr << ')';
written = true;
}
}
if (written)
{
finishFormatWithWindow(ostr, settings, state, frame);
return;
}
/// Empty names are used rarely, to format queries with an extra pair of parentheses for external databases.
if (!name.empty())
ostr << backQuoteIfNeed(name);
if (parameters)
{