forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathASTAlterQuery.cpp
More file actions
1475 lines (1383 loc) · 59 KB
/
Copy pathASTAlterQuery.cpp
File metadata and controls
1475 lines (1383 loc) · 59 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 <Parsers/ASTAlterQuery.h>
#include <Databases/DataLake/DataLakeConstants.h>
#include <IO/Operators.h>
#include <Parsers/ASTJSONHelpers.h>
#include <Parsers/ASTJSONReadHelpers.h>
#include <Parsers/ASTColumnDeclaration.h>
#include <Parsers/ASTIndexDeclaration.h>
#include <Parsers/ASTConstraintDeclaration.h>
#include <Parsers/ASTLiteral.h>
#include <Parsers/ASTPartition.h>
#include <Parsers/ASTProjectionDeclaration.h>
#include <Parsers/ASTQueryParameter.h>
#include <Parsers/ASTStatisticsDeclaration.h>
#include <Parsers/ASTSetQuery.h>
#include <Parsers/ASTSQLSecurity.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTExpressionList.h>
#include <Parsers/ASTAssignment.h>
#include <Parsers/ASTRefreshStrategy.h>
#include <Parsers/ASTSelectWithUnionQuery.h>
#include <Storages/DataDestinationType.h>
#include <base/scope_guard.h>
#include <Common/quoteString.h>
#include <base/EnumReflection.h>
namespace DB
{
namespace ErrorCodes
{
extern const int UNEXPECTED_AST_STRUCTURE;
extern const int BAD_ARGUMENTS;
}
String ASTAlterCommand::getID(char delim) const
{
return fmt::format("AlterCommand{}{}", delim, type);
}
ASTPtr ASTAlterCommand::clone() const
{
auto res = make_intrusive<ASTAlterCommand>(*this);
res->children.clear();
if (col_decl)
res->col_decl = res->children.emplace_back(col_decl->clone()).get();
if (column)
res->column = res->children.emplace_back(column->clone()).get();
if (order_by)
res->order_by = res->children.emplace_back(order_by->clone()).get();
if (sample_by)
res->sample_by = res->children.emplace_back(sample_by->clone()).get();
if (index_decl)
res->index_decl = res->children.emplace_back(index_decl->clone()).get();
if (index)
res->index = res->children.emplace_back(index->clone()).get();
if (constraint_decl)
res->constraint_decl = res->children.emplace_back(constraint_decl->clone()).get();
if (constraint)
res->constraint = res->children.emplace_back(constraint->clone()).get();
if (projection_decl)
res->projection_decl = res->children.emplace_back(projection_decl->clone()).get();
if (projection)
res->projection = res->children.emplace_back(projection->clone()).get();
if (statistics_decl)
res->statistics_decl = res->children.emplace_back(statistics_decl->clone()).get();
if (partition)
res->partition = res->children.emplace_back(partition->clone()).get();
if (predicate)
res->predicate = res->children.emplace_back(predicate->clone()).get();
if (update_assignments)
res->update_assignments = res->children.emplace_back(update_assignments->clone()).get();
if (comment)
res->comment = res->children.emplace_back(comment->clone()).get();
if (ttl)
res->ttl = res->children.emplace_back(ttl->clone()).get();
if (settings_changes)
res->settings_changes = res->children.emplace_back(settings_changes->clone()).get();
if (settings_resets)
res->settings_resets = res->children.emplace_back(settings_resets->clone()).get();
if (select)
res->select = res->children.emplace_back(select->clone()).get();
if (sql_security)
res->sql_security = res->children.emplace_back(sql_security->clone()).get();
if (rename_to)
res->rename_to = res->children.emplace_back(rename_to->clone()).get();
if (execute_args)
res->execute_args = res->children.emplace_back(execute_args->clone()).get();
if (add_enum_values)
res->add_enum_values = res->children.emplace_back(add_enum_values->clone());
if (refresh)
res->refresh = res->children.emplace_back(refresh->clone()).get();
return res;
}
void ASTAlterCommand::writeJSON(WriteBuffer & out) const
{
JSONObjectWriter w(out, "AlterCommand");
w.writeString("command_type", std::string(magic_enum::enum_name(type)));
w.writeBool("detach", detach);
w.writeBool("part", part);
w.writeBool("clear_column", clear_column);
w.writeBool("clear_index", clear_index);
w.writeBool("clear_statistics", clear_statistics);
w.writeBool("clear_projection", clear_projection);
w.writeBool("if_not_exists", if_not_exists);
w.writeBool("if_exists", if_exists);
w.writeBool("first", first);
w.writeBool("replace", replace);
if (type == ASTAlterCommand::MOVE_PARTITION)
w.writeString("move_destination_type", std::string(magic_enum::enum_name(move_destination_type)));
if (!move_destination_name.empty())
w.writeString("move_destination_name", move_destination_name);
if (!from.empty())
w.writeString("from", from);
if (!with_name.empty())
w.writeString("with_name", with_name);
if (!from_database.empty())
w.writeString("from_database", from_database);
if (!from_table.empty())
w.writeString("from_table", from_table);
if (!to_database.empty())
w.writeString("to_database", to_database);
if (!to_table.empty())
w.writeString("to_table", to_table);
if (!snapshot_name.empty())
w.writeString("snapshot_name", snapshot_name);
if (!execute_command_name.empty())
w.writeString("execute_command_name", execute_command_name);
if (!remove_property.empty())
w.writeString("remove_property", remove_property);
w.writeChild("col_decl", col_decl);
w.writeChild("column", column);
w.writeChild("order_by", order_by);
w.writeChild("sample_by", sample_by);
w.writeChild("index_decl", index_decl);
w.writeChild("index", index);
w.writeChild("constraint_decl", constraint_decl);
w.writeChild("constraint", constraint);
w.writeChild("projection_decl", projection_decl);
w.writeChild("projection", projection);
w.writeChild("statistics_decl", statistics_decl);
w.writeChild("partition", partition);
w.writeChild("predicate", predicate);
w.writeChild("update_assignments", update_assignments);
w.writeChild("comment", comment);
w.writeChild("ttl", ttl);
w.writeChild("settings_changes", settings_changes);
w.writeChild("settings_resets", settings_resets);
w.writeChild("select", select);
w.writeChild("sql_security", sql_security);
w.writeChild("rename_to", rename_to);
w.writeChild("refresh", refresh);
w.writeChild("snapshot_desc", snapshot_desc);
w.writeChild("execute_args", execute_args);
/// `ALTER TABLE ... MODIFY COLUMN x ADD ENUM VALUES (...)` stores the new enum values here and
/// `formatImpl` emits the `ADD ENUM VALUES` clause for them; serialize it so the JSON round-trip
/// does not silently drop the clause and change the command's semantics.
w.writeChild("add_enum_values", add_enum_values);
}
void ASTAlterCommand::readJSON(const Poco::JSON::Object & json)
{
JSONObjectReader r(json);
if (!r.has("command_type"))
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Missing 'command_type' field in `AlterCommand` during AST JSON deserialization");
String command_type_str = r.getString("command_type");
auto command_type_opt = magic_enum::enum_cast<Type>(command_type_str);
if (!command_type_opt)
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unknown ALTER command_type: '{}'", command_type_str);
type = *command_type_opt;
detach = r.getBool("detach");
part = r.getBool("part");
clear_column = r.getBool("clear_column");
clear_index = r.getBool("clear_index");
clear_statistics = r.getBool("clear_statistics");
clear_projection = r.getBool("clear_projection");
if_not_exists = r.getBool("if_not_exists");
if_exists = r.getBool("if_exists");
first = r.getBool("first");
replace = r.getBool("replace");
if (r.has("move_destination_type"))
{
String move_dest_type_str = r.getString("move_destination_type");
auto move_dest_opt = magic_enum::enum_cast<DataDestinationType>(move_dest_type_str);
if (!move_dest_opt)
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unknown move_destination_type: '{}'", move_dest_type_str);
move_destination_type = *move_dest_opt;
}
move_destination_name = r.getString("move_destination_name");
from = r.getString("from");
with_name = r.getString("with_name");
from_database = r.getString("from_database");
from_table = r.getString("from_table");
to_database = r.getString("to_database");
to_table = r.getString("to_table");
snapshot_name = r.getString("snapshot_name");
execute_command_name = r.getString("execute_command_name");
remove_property = r.getString("remove_property");
/// `order_by`, `sample_by`, `predicate`, `ttl`, `settings_resets`, `execute_args` and similar
/// are arbitrary expressions/lists with no single parser-produced node type, so they are
/// restored generically.
auto readRawChild = [&](const char * key, IAST *& field)
{
auto child = r.readChild(key);
if (child)
{
field = child.get();
children.push_back(std::move(child));
}
};
/// The remaining children are parser-owned concrete node types that `AlterCommand::parse` and
/// `MutationCommands` downcast unconditionally (e.g. `col_decl` to `ASTColumnDeclaration`, the
/// `*_decl` fields to their declaration nodes, `column`/`index`/`constraint`/`projection`/
/// `rename_to` to `ASTIdentifier`, `settings_changes` to `ASTSetQuery`, `sql_security` to
/// `ASTSQLSecurity`). Restoring them generically would let a wrong node type from malformed
/// `clickhouse_json` reach those downcasts as an internal cast error instead of a user-facing
/// `BAD_ARGUMENTS`, so validate the type at the JSON boundary.
auto readTypedChild = [&]<typename T>(const char * key, IAST *& field)
{
auto child = r.readChildOfType<T>(key);
if (child)
{
field = child.get();
children.push_back(std::move(child));
}
};
readTypedChild.operator()<ASTColumnDeclaration>("col_decl", col_decl);
readTypedChild.operator()<ASTIdentifier>("column", column);
readRawChild("order_by", order_by);
readRawChild("sample_by", sample_by);
readTypedChild.operator()<ASTIndexDeclaration>("index_decl", index_decl);
readTypedChild.operator()<ASTIdentifier>("index", index);
readTypedChild.operator()<ASTConstraintDeclaration>("constraint_decl", constraint_decl);
readTypedChild.operator()<ASTIdentifier>("constraint", constraint);
readTypedChild.operator()<ASTProjectionDeclaration>("projection_decl", projection_decl);
readTypedChild.operator()<ASTIdentifier>("projection", projection);
readTypedChild.operator()<ASTStatisticsDeclaration>("statistics_decl", statistics_decl);
/// `partition` is not an arbitrary expression slot: `ParserAlterQuery` builds it with
/// `ParserPartition` for the `... PARTITION ...` forms and with a string literal or query
/// parameter (`ParserStringAndSubstitution`) for the `... PART ...` forms — the 'part' flag,
/// which the parser produces only for the `DROP`/`DROP DETACHED`/`ATTACH`/`MOVE`/`FETCH`
/// `PART` commands. Execution relies on those shapes: `MergeTreeData::getPartitionIDFromQuery`
/// downcasts the `PARTITION` forms with `->as<ASTPartition &>()` and `getPartNameFromAST`
/// requires a string `ASTLiteral` for `PART`. Restoring the slot generically would let
/// malformed `clickhouse_json` reach those internal casts and could format parser-impossible
/// SQL such as `DROP PART PARTITION 1`, so validate the node shape against the 'part' flag.
if (part)
{
switch (type)
{
case ASTAlterCommand::DROP_PARTITION:
case ASTAlterCommand::DROP_DETACHED_PARTITION:
case ASTAlterCommand::ATTACH_PARTITION:
case ASTAlterCommand::MOVE_PARTITION:
case ASTAlterCommand::FETCH_PARTITION:
break;
default:
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"'part' is only valid for the DROP/DROP DETACHED/ATTACH/MOVE/FETCH PART commands, "
"not '{}', during AST JSON deserialization",
magic_enum::enum_name(type));
}
}
if (auto partition_child = r.readChild("partition"))
{
if (part)
{
const auto * partition_literal = partition_child->as<ASTLiteral>();
if ((!partition_literal || partition_literal->value.getType() != Field::Types::String)
&& !partition_child->as<ASTQueryParameter>())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"'partition' must be a string literal or query parameter for the PART form "
"of an ALTER command during AST JSON deserialization");
}
else if (!partition_child->as<ASTPartition>())
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"'partition' must be a `Partition` node for the PARTITION form of an ALTER command "
"during AST JSON deserialization");
}
partition = partition_child.get();
children.push_back(std::move(partition_child));
}
readRawChild("predicate", predicate);
/// `update_assignments` is an `ASTExpressionList` of `ASTAssignment` (`MutationCommand::parse`
/// downcasts each child to `ASTAssignment`).
readTypedChild.operator()<ASTExpressionList>("update_assignments", update_assignments);
if (update_assignments)
for (const auto & assignment : update_assignments->children)
if (!assignment || !assignment->as<ASTAssignment>())
throw Exception(ErrorCodes::BAD_ARGUMENTS, "ALTER UPDATE 'update_assignments' must contain only assignments during AST JSON deserialization");
/// `comment` (COMMENT COLUMN / MODIFY COMMENT / MODIFY DATABASE COMMENT) is parsed by
/// `ParserStringLiteral`; `AlterCommands` reads `comment->as<ASTLiteral &>().value.safeGet<String>()`,
/// so require a string literal (not merely an `ASTLiteral`) here.
if (auto comment_child = r.readStringLiteralChild("comment"))
{
comment = comment_child.get();
children.push_back(std::move(comment_child));
}
readRawChild("ttl", ttl);
readTypedChild.operator()<ASTSetQuery>("settings_changes", settings_changes);
/// `settings_resets` is an `ASTExpressionList` of `ASTIdentifier` (the reset setting names).
readTypedChild.operator()<ASTExpressionList>("settings_resets", settings_resets);
if (settings_resets)
for (const auto & setting : settings_resets->children)
if (!setting || !setting->as<ASTIdentifier>())
throw Exception(ErrorCodes::BAD_ARGUMENTS, "ALTER 'settings_resets' must contain only setting identifiers during AST JSON deserialization");
/// `select` (MODIFY QUERY) is an `ASTSelectWithUnionQuery`; `refresh` (MODIFY REFRESH) an `ASTRefreshStrategy`.
readTypedChild.operator()<ASTSelectWithUnionQuery>("select", select);
readTypedChild.operator()<ASTSQLSecurity>("sql_security", sql_security);
readTypedChild.operator()<ASTIdentifier>("rename_to", rename_to);
readRawChild("snapshot_desc", snapshot_desc);
readRawChild("execute_args", execute_args);
readTypedChild.operator()<ASTRefreshStrategy>("refresh", refresh);
/// `ADD ENUM VALUES (...)` is parser-produced as an `ASTExpressionList`; `formatImpl` emits it
/// for `MODIFY_COLUMN`, so it must round-trip through JSON (see `writeJSON`).
add_enum_values = r.readChildOfType<ASTExpressionList>("add_enum_values");
if (add_enum_values)
children.push_back(add_enum_values);
/// Validate that all children required by `formatImpl` for this command type are present.
/// Without this, a malformed JSON could produce a command whose `formatImpl` dereferences a null member.
auto require = [&](const IAST * field, const char * field_name)
{
if (!field)
throw Exception(
ErrorCodes::BAD_ARGUMENTS,
"Missing required '{}' field for ALTER command of type '{}' during AST JSON deserialization",
field_name, magic_enum::enum_name(type));
};
switch (type)
{
case ASTAlterCommand::ADD_COLUMN:
require(col_decl, "col_decl");
break;
case ASTAlterCommand::DROP_COLUMN:
require(column, "column");
break;
case ASTAlterCommand::MODIFY_COLUMN:
{
require(col_decl, "col_decl");
/// `MODIFY COLUMN` has exactly one parser sub-form: `REMOVE <prop>`, `MODIFY SETTING ...`,
/// `RESET SETTING ...`, `ADD ENUM VALUES (...)`, or the plain modify (optionally `FIRST`/
/// `AFTER`). `formatImpl` prints only the first matching sub-form, but `AlterCommand::parse`
/// still copies the hidden fields (`metadata.columns.modify` applies `first`/`after_column`,
/// `settings_changes`, `settings_resets`), so a payload could execute a reorder or setting
/// reset that the formatted SQL hides. Reject parser-impossible combinations: at most one
/// sub-form, and `first`/`column` (AFTER) only for the plain modify form.
const int sub_forms = static_cast<int>(!remove_property.empty()) + static_cast<int>(settings_changes != nullptr)
+ static_cast<int>(settings_resets != nullptr) + static_cast<int>(add_enum_values != nullptr);
if (sub_forms > 1)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"`MODIFY COLUMN` cannot combine REMOVE / MODIFY SETTING / RESET SETTING / ADD ENUM VALUES during AST JSON deserialization");
if (sub_forms == 1 && (first || column))
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"`MODIFY COLUMN` 'first'/'column' (AFTER) are only valid for the plain modify form during AST JSON deserialization");
if (first && column)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"`MODIFY COLUMN` cannot set both 'first' (FIRST) and 'column' (AFTER) during AST JSON deserialization");
break;
}
case ASTAlterCommand::MATERIALIZE_COLUMN:
require(column, "column");
break;
case ASTAlterCommand::COMMENT_COLUMN:
require(column, "column");
require(comment, "comment");
break;
case ASTAlterCommand::MODIFY_COMMENT:
case ASTAlterCommand::MODIFY_DATABASE_COMMENT:
require(comment, "comment");
break;
case ASTAlterCommand::MODIFY_ORDER_BY:
require(order_by, "order_by");
break;
case ASTAlterCommand::MODIFY_SAMPLE_BY:
require(sample_by, "sample_by");
break;
case ASTAlterCommand::ADD_INDEX:
require(index_decl, "index_decl");
/// The parser produces either `FIRST` or `AFTER <index>`, never both. `formatImpl` prints
/// only `FIRST`, but `AlterCommand::apply` lets `after_index_name` override the `first`
/// insertion position, so a payload with both would format as `ADD INDEX ... FIRST` while
/// inserting after another index. Reject the parser-impossible combination.
if (first && index)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"`ADD INDEX` cannot set both 'first' (FIRST) and 'column' (AFTER) during AST JSON deserialization");
break;
case ASTAlterCommand::DROP_INDEX:
case ASTAlterCommand::MATERIALIZE_INDEX:
require(index, "index");
break;
case ASTAlterCommand::ADD_STATISTICS:
case ASTAlterCommand::MODIFY_STATISTICS:
require(statistics_decl, "statistics_decl");
/// `ADD`/`MODIFY STATISTICS` are parsed with `ParserStatisticsDeclaration` (a `TYPE` list);
/// `AlterCommand::parse` unconditionally calls `ASTStatisticsDeclaration::getTypeNames`, which
/// asserts `types != nullptr`. Reject the no-types declaration shape here.
if (!statistics_decl->as<ASTStatisticsDeclaration &>().types)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"ADD/MODIFY STATISTICS requires a TYPE list ('statistics_decl' must have 'types') during AST JSON deserialization");
break;
case ASTAlterCommand::MATERIALIZE_STATISTICS:
/// `MATERIALIZE STATISTICS ALL` is parser-produced with a null declaration (`writeJSON` omits
/// it and `formatImpl` emits `ALL`); the column-list form carries one. Allow the null form, but
/// reject a `TYPE` list when a declaration is present (parser-impossible:
/// `ParserStatisticsDeclarationWithoutTypes`).
if (statistics_decl && statistics_decl->as<ASTStatisticsDeclaration &>().types)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"MATERIALIZE STATISTICS must not carry a TYPE list ('statistics_decl' 'types') during AST JSON deserialization");
/// `IF EXISTS` and `IN PARTITION` are parsed only in the column-list branch, so the `ALL` form
/// (null declaration) never carries either, and `formatImpl` has nowhere to print them.
if (if_exists && !statistics_decl)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"MATERIALIZE STATISTICS ALL (no 'statistics_decl') must not set 'if_exists' during AST JSON deserialization");
if (partition && !statistics_decl)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"MATERIALIZE STATISTICS ALL (no 'statistics_decl') must not set 'partition' during AST JSON deserialization");
break;
case ASTAlterCommand::DROP_STATISTICS:
/// `CLEAR STATISTICS ALL` (`clear_statistics`) is parser-produced with a null declaration; plain
/// `DROP STATISTICS` and the non-`ALL` `CLEAR STATISTICS <cols>` form always carry a column-list
/// declaration. A `TYPE` list is parser-impossible for any of them.
if (!clear_statistics)
require(statistics_decl, "statistics_decl");
if (statistics_decl && statistics_decl->as<ASTStatisticsDeclaration &>().types)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"DROP/CLEAR STATISTICS must not carry a TYPE list ('statistics_decl' 'types') during AST JSON deserialization");
/// `IF EXISTS` and `IN PARTITION` are parsed only where a column-list declaration is also
/// required, so the `CLEAR STATISTICS ALL` form (null declaration) never carries either:
/// `IF EXISTS ALL` reparses as a column named `ALL`, `ALL IN PARTITION p` not at all.
if (if_exists && !statistics_decl)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"CLEAR STATISTICS ALL (no 'statistics_decl') must not set 'if_exists' during AST JSON deserialization");
if (partition && !statistics_decl)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"CLEAR STATISTICS ALL (no 'statistics_decl') must not set 'partition' during AST JSON deserialization");
break;
case ASTAlterCommand::ADD_CONSTRAINT:
require(constraint_decl, "constraint_decl");
break;
case ASTAlterCommand::DROP_CONSTRAINT:
require(constraint, "constraint");
break;
case ASTAlterCommand::ADD_PROJECTION:
case ASTAlterCommand::MODIFY_PROJECTION:
require(projection_decl, "projection_decl");
break;
case ASTAlterCommand::DROP_PROJECTION:
case ASTAlterCommand::MATERIALIZE_PROJECTION:
require(projection, "projection");
break;
case ASTAlterCommand::DROP_PARTITION:
case ASTAlterCommand::DROP_DETACHED_PARTITION:
case ASTAlterCommand::FORGET_PARTITION:
case ASTAlterCommand::ATTACH_PARTITION:
case ASTAlterCommand::FREEZE_PARTITION:
require(partition, "partition");
break;
case ASTAlterCommand::REPLACE_PARTITION:
/// `[ATTACH|REPLACE] PARTITION ... FROM [db.]table` — the parser always parses a source table
/// (`from_database` is optional, defaulting to the current database). `formatImpl` emits
/// `FROM <from_table>`, so an empty `from_table` would format a parser-impossible `FROM `.
require(partition, "partition");
if (from_table.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"REPLACE/ATTACH PARTITION FROM requires a non-empty 'from_table' during AST JSON deserialization");
break;
case ASTAlterCommand::FETCH_PARTITION:
/// `FETCH PART[ITION] ... FROM '<path>'` — the parser always requires the `FROM` path; an empty
/// path is never a valid source. `formatImpl` emits `FROM <from>`.
require(partition, "partition");
if (from.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"FETCH PARTITION requires a non-empty 'from' (FROM path) during AST JSON deserialization");
break;
case ASTAlterCommand::UNFREEZE_PARTITION:
/// `UNFREEZE PARTITION ... WITH NAME '<name>'` — unlike `FREEZE`, the parser requires `WITH NAME`,
/// so the backup name must be present. `formatImpl` only emits `WITH NAME` for a non-empty name.
require(partition, "partition");
if (with_name.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"UNFREEZE PARTITION requires a non-empty 'with_name' (WITH NAME) during AST JSON deserialization");
break;
case ASTAlterCommand::UNFREEZE_ALL:
/// `UNFREEZE WITH NAME '<name>'` — the parser requires `WITH NAME` for the all-partitions form too.
if (with_name.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"UNFREEZE requires a non-empty 'with_name' (WITH NAME) during AST JSON deserialization");
break;
case ASTAlterCommand::MOVE_PARTITION:
require(partition, "partition");
/// `writeJSON` only emits `move_destination_type` for `MOVE_PARTITION`, so it must be present here.
if (!r.has("move_destination_type"))
throw Exception(
ErrorCodes::BAD_ARGUMENTS,
"Missing required 'move_destination_type' field for ALTER command of type 'MOVE_PARTITION' "
"during AST JSON deserialization");
switch (move_destination_type)
{
case DataDestinationType::DISK:
case DataDestinationType::VOLUME:
case DataDestinationType::SHARD:
/// `TO SHARD` exists only in the `MOVE PART` grammar branch, and
/// `movePartitionToShard` reads the part name off an `ASTLiteral`.
if (move_destination_type == DataDestinationType::SHARD && !part)
throw Exception(
ErrorCodes::BAD_ARGUMENTS,
"move_destination_type 'SHARD' requires the PART form ('part' set) of MOVE "
"during AST JSON deserialization");
if (move_destination_name.empty())
throw Exception(
ErrorCodes::BAD_ARGUMENTS,
"Missing required 'move_destination_name' field for ALTER command of type 'MOVE_PARTITION' "
"with move_destination_type '{}' during AST JSON deserialization",
magic_enum::enum_name(move_destination_type));
break;
case DataDestinationType::TABLE:
/// `TO TABLE` exists only in the `MOVE PARTITION` grammar branch, and
/// `getPartitionIDFromQuery` downcasts `partition` to `ASTPartition`.
if (part)
throw Exception(
ErrorCodes::BAD_ARGUMENTS,
"move_destination_type 'TABLE' requires the PARTITION form ('part' unset) of MOVE "
"during AST JSON deserialization");
if (to_table.empty())
throw Exception(
ErrorCodes::BAD_ARGUMENTS,
"Missing required 'to_table' field for ALTER command of type 'MOVE_PARTITION' "
"with move_destination_type 'TABLE' during AST JSON deserialization");
break;
default:
throw Exception(
ErrorCodes::BAD_ARGUMENTS,
"Unsupported move_destination_type '{}' for ALTER command of type 'MOVE_PARTITION' "
"during AST JSON deserialization",
magic_enum::enum_name(move_destination_type));
}
break;
case ASTAlterCommand::DELETE:
require(predicate, "predicate");
break;
case ASTAlterCommand::UPDATE:
require(update_assignments, "update_assignments");
require(predicate, "predicate");
break;
case ASTAlterCommand::MODIFY_TTL:
require(ttl, "ttl");
break;
case ASTAlterCommand::MODIFY_SETTING:
case ASTAlterCommand::MODIFY_DATABASE_SETTING:
require(settings_changes, "settings_changes");
break;
case ASTAlterCommand::RESET_SETTING:
require(settings_resets, "settings_resets");
break;
case ASTAlterCommand::MODIFY_QUERY:
require(select, "select");
break;
case ASTAlterCommand::MODIFY_REFRESH:
require(refresh, "refresh");
break;
case ASTAlterCommand::RENAME_COLUMN:
require(column, "column");
require(rename_to, "rename_to");
break;
case ASTAlterCommand::MODIFY_SQL_SECURITY:
require(sql_security, "sql_security");
break;
default:
break;
}
/// `IN PARTITION` is parser-produced only for the `CLEAR` forms (and the materialize forms), never for
/// the metadata-only `DROP COLUMN/INDEX/STATISTICS/PROJECTION` variants. `formatImpl` would emit a
/// parser-impossible `DROP ... IN PARTITION`, and `AlterCommand::apply` skips metadata removal whenever
/// a partition is present (and `tryConvertToMutationCommand` reparses the formatted text). Reject a
/// `partition` on the drop variants (`clear_*` flag false); `CLEAR`/materialize forms keep it.
if (partition)
{
if ((type == ASTAlterCommand::DROP_COLUMN && !clear_column)
|| (type == ASTAlterCommand::DROP_INDEX && !clear_index)
|| (type == ASTAlterCommand::DROP_STATISTICS && !clear_statistics)
|| (type == ASTAlterCommand::DROP_PROJECTION && !clear_projection))
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"'partition' (IN PARTITION) is only valid for the CLEAR/MATERIALIZE forms, not a metadata DROP, during AST JSON deserialization");
}
}
void ASTAlterCommand::formatImpl(WriteBuffer & ostr, const FormatSettings & settings, FormatState & state, FormatStateStacked frame) const
{
ostr << "(";
auto closing_bracket_guard = make_scope_guard(std::function<void(void)>([&ostr]() { ostr << ")"; }));
if (type == ASTAlterCommand::ADD_COLUMN)
{
ostr << "ADD COLUMN " << (if_not_exists ? "IF NOT EXISTS " : "")
;
col_decl->format(ostr, settings, state, frame);
if (first)
ostr << " FIRST ";
else if (column) /// AFTER
{
ostr << " AFTER ";
column->format(ostr, settings, state, frame);
}
}
else if (type == ASTAlterCommand::DROP_COLUMN)
{
ostr << (clear_column ? "CLEAR " : "DROP ") << "COLUMN "
<< (if_exists ? "IF EXISTS " : "");
column->format(ostr, settings, state, frame);
if (partition)
{
ostr << " IN PARTITION ";
partition->format(ostr, settings, state, frame);
}
}
else if (type == ASTAlterCommand::MODIFY_COLUMN)
{
ostr << "MODIFY COLUMN " << (if_exists ? "IF EXISTS " : "")
;
col_decl->format(ostr, settings, state, frame);
if (!remove_property.empty())
{
ostr << " REMOVE " << remove_property;
}
else if (settings_changes)
{
ostr << " MODIFY SETTING ";
settings_changes->format(ostr, settings, state, frame);
}
else if (settings_resets)
{
ostr << " RESET SETTING ";
settings_resets->format(ostr, settings, state, frame);
}
else if (add_enum_values)
{
ostr << " ADD ENUM VALUES (";
ostr << " ";
add_enum_values->format(ostr, settings, state, frame);
ostr << " )";
ostr << " ";
}
else
{
if (first)
ostr << " FIRST ";
else if (column) /// AFTER
{
ostr << " AFTER ";
column->format(ostr, settings, state, frame);
}
}
}
else if (type == ASTAlterCommand::MATERIALIZE_COLUMN)
{
ostr << "MATERIALIZE COLUMN ";
column->format(ostr, settings, state, frame);
if (partition)
{
ostr << " IN PARTITION ";
partition->format(ostr, settings, state, frame);
}
}
else if (type == ASTAlterCommand::COMMENT_COLUMN)
{
ostr << "COMMENT COLUMN " << (if_exists ? "IF EXISTS " : "")
;
column->format(ostr, settings, state, frame);
ostr << " ";
comment->format(ostr, settings, state, frame);
}
else if (type == ASTAlterCommand::MODIFY_COMMENT || type == ASTAlterCommand::MODIFY_DATABASE_COMMENT)
{
ostr << "MODIFY COMMENT";
ostr << " ";
comment->format(ostr, settings, state, frame);
}
else if (type == ASTAlterCommand::MODIFY_ORDER_BY)
{
ostr << "MODIFY ORDER BY ";
order_by->format(ostr, settings, state, frame);
}
else if (type == ASTAlterCommand::MODIFY_SAMPLE_BY)
{
ostr << "MODIFY SAMPLE BY ";
sample_by->format(ostr, settings, state, frame);
}
else if (type == ASTAlterCommand::REMOVE_SAMPLE_BY)
{
ostr << "REMOVE SAMPLE BY";
}
else if (type == ASTAlterCommand::ADD_INDEX)
{
ostr << "ADD INDEX " << (if_not_exists ? "IF NOT EXISTS " : "")
;
index_decl->format(ostr, settings, state, frame);
if (first)
ostr << " FIRST ";
else if (index) /// AFTER
{
ostr << " AFTER ";
index->format(ostr, settings, state, frame);
}
}
else if (type == ASTAlterCommand::DROP_INDEX)
{
ostr << (clear_index ? "CLEAR " : "DROP ") << "INDEX "
<< (if_exists ? "IF EXISTS " : "");
index->format(ostr, settings, state, frame);
if (partition)
{
ostr << " IN PARTITION ";
partition->format(ostr, settings, state, frame);
}
}
else if (type == ASTAlterCommand::MATERIALIZE_INDEX)
{
ostr << "MATERIALIZE INDEX " << (if_exists ? "IF EXISTS " : "");
index->format(ostr, settings, state, frame);
if (partition)
{
ostr << " IN PARTITION ";
partition->format(ostr, settings, state, frame);
}
}
else if (type == ASTAlterCommand::ADD_STATISTICS)
{
ostr << "ADD STATISTICS " << (if_not_exists ? "IF NOT EXISTS " : "")
;
statistics_decl->format(ostr, settings, state, frame);
}
else if (type == ASTAlterCommand::MODIFY_STATISTICS)
{
ostr << "MODIFY STATISTICS "
;
statistics_decl->format(ostr, settings, state, frame);
}
else if (type == ASTAlterCommand::DROP_STATISTICS)
{
ostr << (clear_statistics ? "CLEAR " : "DROP ") << "STATISTICS "
<< (if_exists ? "IF EXISTS " : "");
if (statistics_decl)
statistics_decl->format(ostr, settings, state, frame);
else
ostr << " ALL";
if (partition)
{
ostr << " IN PARTITION ";
partition->format(ostr, settings, state, frame);
}
}
else if (type == ASTAlterCommand::MATERIALIZE_STATISTICS)
{
ostr << "MATERIALIZE STATISTICS ";
if (statistics_decl)
{
/// Only the column-list form accepts `IF EXISTS`; on the `ALL` form the clause would
/// reparse as a column named `ALL`.
ostr << (if_exists ? "IF EXISTS " : "");
statistics_decl->format(ostr, settings, state, frame);
if (partition)
{
ostr << " IN PARTITION ";
partition->format(ostr, settings, state, frame);
}
}
else
ostr << " ALL";
}
else if (type == ASTAlterCommand::UNLOCK_SNAPSHOT)
{
ostr << "UNLOCK SNAPSHOT ";
ostr << quoteString(snapshot_name);
if (snapshot_desc != nullptr)
{
ostr << " FROM ";
snapshot_desc->format(ostr, settings, state, frame);
}
}
else if (type == ASTAlterCommand::ADD_CONSTRAINT)
{
ostr << "ADD CONSTRAINT " << (if_not_exists ? "IF NOT EXISTS " : "")
;
constraint_decl->format(ostr, settings, state, frame);
}
else if (type == ASTAlterCommand::DROP_CONSTRAINT)
{
ostr << "DROP CONSTRAINT " << (if_exists ? "IF EXISTS " : "")
;
constraint->format(ostr, settings, state, frame);
}
else if (type == ASTAlterCommand::MODIFY_CONSTRAINT)
{
ostr << "MODIFY CONSTRAINT " << (if_exists ? "IF EXISTS " : "")
;
constraint_decl->format(ostr, settings, state, frame);
}
else if (type == ASTAlterCommand::ADD_PROJECTION)
{
ostr << "ADD PROJECTION " << (if_not_exists ? "IF NOT EXISTS " : "")
;
projection_decl->format(ostr, settings, state, frame);
if (first)
ostr << " FIRST ";
else if (projection)
{
ostr << " AFTER ";
projection->format(ostr, settings, state, frame);
}
}
else if (type == ASTAlterCommand::MODIFY_PROJECTION)
{
ostr << "MODIFY PROJECTION " << (if_exists ? "IF EXISTS " : "");
projection_decl->format(ostr, settings, state, frame);
}
else if (type == ASTAlterCommand::DROP_PROJECTION)
{
ostr << (clear_projection ? "CLEAR " : "DROP ") << "PROJECTION "
<< (if_exists ? "IF EXISTS " : "");
projection->format(ostr, settings, state, frame);
if (partition)
{
ostr << " IN PARTITION ";
partition->format(ostr, settings, state, frame);
}
}
else if (type == ASTAlterCommand::MATERIALIZE_PROJECTION)
{
ostr << "MATERIALIZE PROJECTION " << (if_exists ? "IF EXISTS " : "");
projection->format(ostr, settings, state, frame);
if (partition)
{
ostr << " IN PARTITION ";
partition->format(ostr, settings, state, frame);
}
}
else if (type == ASTAlterCommand::DROP_PARTITION)
{
ostr << (detach ? "DETACH" : "DROP") << (part ? " PART " : " PARTITION ")
;
partition->format(ostr, settings, state, frame);
}
else if (type == ASTAlterCommand::DROP_DETACHED_PARTITION)
{
ostr << "DROP DETACHED" << (part ? " PART " : " PARTITION ")
;
partition->format(ostr, settings, state, frame);
}
else if (type == ASTAlterCommand::FORGET_PARTITION)
{
ostr << "FORGET PARTITION "
;
partition->format(ostr, settings, state, frame);
}
else if (type == ASTAlterCommand::ATTACH_PARTITION)
{
ostr << "ATTACH " << (part ? "PART " : "PARTITION ")
;
partition->format(ostr, settings, state, frame);
/// `ATTACH PART '...' FROM '<path>'` stores the source path in `from` (the parser only sets it for
/// the PART form). `PartitionCommand::parse` consumes it as `from_path`, so the path must be emitted
/// for the JSON round trip; otherwise the formatted SQL would hide the source the command uses.
if (part && !from.empty())
ostr << " FROM " << DB::quote << from;
}
else if (type == ASTAlterCommand::MOVE_PARTITION)
{
ostr << "MOVE " << (part ? "PART " : "PARTITION ")
;
partition->format(ostr, settings, state, frame);
ostr << " TO ";
switch (move_destination_type)
{
case DataDestinationType::DISK:
ostr << "DISK ";
break;
case DataDestinationType::VOLUME:
ostr << "VOLUME ";
break;
case DataDestinationType::SHARD:
ostr << "SHARD ";
break;
case DataDestinationType::TABLE:
ostr << "TABLE ";
if (!to_database.empty())
{
ostr << backQuoteIfNeed(to_database)
<< ".";
}
ostr << backQuoteIfNeed(to_table)
;
return;
default:
break;
}
if (move_destination_type != DataDestinationType::TABLE)
{
ostr << quoteString(move_destination_name);
}
}
else if (type == ASTAlterCommand::REPLACE_PARTITION)
{
ostr << (replace ? "REPLACE" : "ATTACH") << " PARTITION "
;
partition->format(ostr, settings, state, frame);
ostr << " FROM ";
if (!from_database.empty())
{
ostr << backQuoteIfNeed(from_database)
<< ".";
}
ostr << backQuoteIfNeed(from_table);
}
else if (type == ASTAlterCommand::FETCH_PARTITION)
{
ostr << "FETCH " << (part ? "PART " : "PARTITION ")
;
partition->format(ostr, settings, state, frame);
ostr << " FROM " << DB::quote << from;
}
else if (type == ASTAlterCommand::FREEZE_PARTITION)
{
ostr << "FREEZE PARTITION ";
partition->format(ostr, settings, state, frame);
if (!with_name.empty())
{
ostr << " " << "WITH NAME" << " "
<< DB::quote << with_name;
}
}
else if (type == ASTAlterCommand::FREEZE_ALL)
{
ostr << "FREEZE";
if (!with_name.empty())
{
ostr << " " << "WITH NAME" << " "
<< DB::quote << with_name;
}
}
else if (type == ASTAlterCommand::UNFREEZE_PARTITION)
{
ostr << "UNFREEZE PARTITION ";
partition->format(ostr, settings, state, frame);
if (!with_name.empty())
{
ostr << " " << "WITH NAME" << " "
<< DB::quote << with_name;
}
}
else if (type == ASTAlterCommand::UNFREEZE_ALL)
{
ostr << "UNFREEZE";
if (!with_name.empty())
{
ostr << " " << "WITH NAME" << " "
<< DB::quote << with_name;
}
}
else if (type == ASTAlterCommand::DELETE)
{
ostr << "DELETE";
if (partition)
{
ostr << " IN PARTITION ";
partition->format(ostr, settings, state, frame);
}
ostr << " WHERE ";