forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathASTCreateQuery.cpp
More file actions
1212 lines (1055 loc) · 46.8 KB
/
Copy pathASTCreateQuery.cpp
File metadata and controls
1212 lines (1055 loc) · 46.8 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/ASTCreateQuery.h>
#include <Parsers/ASTColumnDeclaration.h>
#include <Parsers/ASTConstraintDeclaration.h>
#include <Parsers/ASTDictionaryAttributeDeclaration.h>
#include <Parsers/ASTExpressionList.h>
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTIndexDeclaration.h>
#include <Parsers/ASTLiteral.h>
#include <Parsers/ASTTTLElement.h>
#include <Parsers/ASTProjectionDeclaration.h>
#include <Parsers/ASTSQLSecurity.h>
#include <Parsers/ASTSelectWithUnionQuery.h>
#include <Parsers/ASTSetQuery.h>
#include <Parsers/ASTWithAlias.h>
#include <Parsers/CommonParsers.h>
#include <Parsers/CreateQueryUUIDs.h>
#include <Common/quoteString.h>
#include <Interpreters/StorageID.h>
#include <IO/Operators.h>
#include <IO/ReadHelpers.h>
#include <IO/WriteBufferFromString.h>
#include <Parsers/ASTJSONHelpers.h>
#include <Parsers/ASTJSONReadHelpers.h>
#include <Core/UUID.h>
namespace DB
{
namespace ErrorCodes
{
extern const int BAD_ARGUMENTS;
}
ASTPtr ASTStorage::clone() const
{
auto res = make_intrusive<ASTStorage>(*this);
res->children.clear();
/// Children must be added in the canonical order used by `formatImpl` and
/// `normalizeChildrenOrder`. `IAST::updateTreeHash` iterates `children` in sequence.
if (engine)
res->set(res->engine, engine->clone());
if (partition_by)
res->set(res->partition_by, partition_by->clone());
if (primary_key)
res->set(res->primary_key, primary_key->clone());
if (order_by)
res->set(res->order_by, order_by->clone());
if (unique_key)
res->set(res->unique_key, unique_key->clone());
if (sample_by)
res->set(res->sample_by, sample_by->clone());
if (ttl_table)
res->set(res->ttl_table, ttl_table->clone());
if (settings)
res->set(res->settings, settings->clone());
return res;
}
void ASTColumns::writeJSON(WriteBuffer & out) const
{
JSONObjectWriter w(out, "Columns definition");
w.writeChild("columns", columns);
w.writeChild("indices", indices);
w.writeChild("constraints", constraints);
w.writeChild("projections", projections);
/// `primary_key`/`primary_key_from_columns` are parser-intermediate slots that are always cleared
/// on the final AST, so for any parser-produced query nothing is emitted here. They are still
/// written (rather than skipped) so that a parser-impossible in-memory AST fails loudly in
/// `readJSON` instead of losing the hidden primary-key state silently.
w.writeChild("primary_key", primary_key);
w.writeChild("primary_key_from_columns", primary_key_from_columns);
}
void ASTColumns::readJSON(const Poco::JSON::Object & json)
{
JSONObjectReader r(json);
/// `columns`/`indices`/`constraints`/`projections` are parser-produced `ASTExpressionList`s whose
/// children are concrete declaration nodes. Both layers are downcast later (a wrong outer type makes
/// `set` raise `LOGICAL_ERROR`; a wrong child reaches code such as `getColumnsDescription`, which does
/// `ast->as<ASTColumnDeclaration &>()`). Validate both so malformed `clickhouse_json` fails closed.
auto readDeclarationList = [&]<typename T>(const char * key, ASTExpressionList *& member)
{
auto child = r.readChildOfType<ASTExpressionList>(key);
if (!child)
return;
for (const auto & element : child->children)
if (!element || !element->as<T>())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Unexpected element type in '{}' of `Columns` during AST JSON deserialization", key);
set(member, child);
};
readDeclarationList.operator()<ASTColumnDeclaration>("columns", columns);
readDeclarationList.operator()<ASTIndexDeclaration>("indices", indices);
readDeclarationList.operator()<ASTConstraintDeclaration>("constraints", constraints);
readDeclarationList.operator()<ASTProjectionDeclaration>("projections", projections);
/// `primary_key`/`primary_key_from_columns` are parser-intermediate slots: `ParserCreateQuery`
/// normalizes them into `storage->primary_key` and resets them here before returning the final AST,
/// and both `ASTColumns::formatImpl` and `InterpreterCreateQuery` ignore them afterwards. Accepting
/// them from JSON would carry a hidden primary-key request that formatting and execution silently
/// drop, so reject them as parser-impossible.
if (r.has("primary_key") || r.has("primary_key_from_columns"))
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"'primary_key' and 'primary_key_from_columns' are not allowed in `Columns` during AST JSON deserialization");
}
void ASTStorage::writeJSON(WriteBuffer & out) const
{
JSONObjectWriter w(out, "Storage");
w.writeChild("engine", engine);
w.writeChild("partition_by", partition_by);
w.writeChild("primary_key", primary_key);
w.writeChild("order_by", order_by);
w.writeChild("unique_key", unique_key);
w.writeChild("sample_by", sample_by);
w.writeChild("ttl_table", ttl_table);
w.writeChild("settings", settings);
}
void ASTStorage::readJSON(const Poco::JSON::Object & json)
{
JSONObjectReader r(json);
/// `engine` (`ASTFunction`) and `settings` (`ASTSetQuery`) are concrete typed members; a wrong node
/// type from malformed `clickhouse_json` would otherwise reach `set` as a `LOGICAL_ERROR` cast
/// failure instead of a user-facing `BAD_ARGUMENTS`. The remaining slots are arbitrary expressions.
auto child = r.readChildOfType<ASTFunction>("engine");
if (child)
set(engine, child);
child = r.readChild("partition_by");
if (child)
set(partition_by, child);
child = r.readChild("primary_key");
if (child)
set(primary_key, child);
child = r.readChild("order_by");
if (child)
set(order_by, child);
child = r.readChild("unique_key");
if (child)
set(unique_key, child);
child = r.readChild("sample_by");
if (child)
set(sample_by, child);
/// `ttl_table` is the `ASTExpressionList` produced by `ParserTTLExpressionList`;
/// `TTLTableDescription::getTTLForTableFromAST` iterates `definition_ast->children`, each an
/// `ASTTTLElement`. Reject any other node type (or non-TTL children) so malformed `clickhouse_json`
/// cannot format as `TTL ...` while execution applies no table TTL (an `Identifier` has no children).
child = r.readChildOfType<ASTExpressionList>("ttl_table");
if (child)
{
for (const auto & ttl_element : child->children)
if (!ttl_element || !ttl_element->as<ASTTTLElement>())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"`ttl_table` must be a list of TTL elements during AST JSON deserialization");
set(ttl_table, child);
}
child = r.readChildOfType<ASTSetQuery>("settings");
if (child)
set(settings, child);
}
void ASTStorage::formatImpl(WriteBuffer & ostr, const FormatSettings & s, FormatState & state, FormatStateStacked frame) const
{
auto modified_frame{frame};
if (engine)
{
modified_frame.create_engine_name = engine->name;
ostr << s.nl_or_ws << "ENGINE" << " = ";
engine->format(ostr, s, state, modified_frame);
}
if (partition_by)
{
ostr << s.nl_or_ws << "PARTITION BY ";
auto nested_frame = modified_frame;
if (auto * ast_alias = dynamic_cast<ASTWithAlias *>(partition_by); ast_alias && !ast_alias->tryGetAlias().empty())
nested_frame.need_parens = true;
partition_by->format(ostr, s, state, nested_frame);
}
if (primary_key)
{
ostr << s.nl_or_ws << "PRIMARY KEY ";
auto nested_frame = modified_frame;
if (auto * ast_alias = dynamic_cast<ASTWithAlias *>(primary_key); ast_alias && !ast_alias->tryGetAlias().empty())
nested_frame.need_parens = true;
primary_key->format(ostr, s, state, nested_frame);
}
if (order_by)
{
ostr << s.nl_or_ws << "ORDER BY ";
auto nested_frame = modified_frame;
if (auto * ast_alias = dynamic_cast<ASTWithAlias *>(order_by); ast_alias && !ast_alias->tryGetAlias().empty())
nested_frame.need_parens = true;
order_by->format(ostr, s, state, nested_frame);
}
if (unique_key)
{
ostr << s.nl_or_ws << "UNIQUE KEY ";
auto nested_frame = modified_frame;
if (auto * ast_alias = dynamic_cast<ASTWithAlias *>(unique_key); ast_alias && !ast_alias->tryGetAlias().empty())
nested_frame.need_parens = true;
unique_key->format(ostr, s, state, nested_frame);
}
if (sample_by)
{
ostr << s.nl_or_ws << "SAMPLE BY ";
auto nested_frame = modified_frame;
if (auto * ast_alias = dynamic_cast<ASTWithAlias *>(sample_by); ast_alias && !ast_alias->tryGetAlias().empty())
nested_frame.need_parens = true;
sample_by->format(ostr, s, state, nested_frame);
}
if (ttl_table)
{
ostr << s.nl_or_ws << "TTL ";
ttl_table->format(ostr, s, state, modified_frame);
}
if (settings)
{
ostr << s.nl_or_ws << "SETTINGS ";
settings->format(ostr, s, state, modified_frame);
}
}
void ASTStorage::normalizeChildrenOrder()
{
/// Keep old children alive while we rebuild the vector, because the raw
/// member pointers (engine, primary_key, …) do not hold ownership —
/// the intrusive_ptrs in `children` do. Clearing first would destroy
/// the objects and leave dangling raw pointers.
ASTs old_children;
old_children.swap(children);
if (engine) children.emplace_back(engine);
if (partition_by) children.emplace_back(partition_by);
if (primary_key) children.emplace_back(primary_key);
if (order_by) children.emplace_back(order_by);
if (unique_key) children.emplace_back(unique_key);
if (sample_by) children.emplace_back(sample_by);
if (ttl_table) children.emplace_back(ttl_table);
if (settings) children.emplace_back(settings);
}
bool ASTStorage::isExtendedStorageDefinition() const
{
return partition_by || primary_key || order_by || unique_key || sample_by || settings;
}
class ASTColumnsElement : public IAST
{
public:
String prefix;
IAST * elem{};
String getID(char c) const override { return "ASTColumnsElement for " + elem->getID(c); }
ASTPtr clone() const override;
void forEachPointerToChild(std::function<void(IAST **, boost::intrusive_ptr<IAST> *)> f) override
{
f(&elem, nullptr);
}
protected:
void formatImpl(WriteBuffer & ostr, const FormatSettings & s, FormatState & state, FormatStateStacked frame) const override;
};
ASTPtr ASTColumnsElement::clone() const
{
auto res = make_intrusive<ASTColumnsElement>();
res->prefix = prefix;
if (elem)
res->set(res->elem, elem->clone());
return res;
}
void ASTColumnsElement::formatImpl(WriteBuffer & ostr, const FormatSettings & s, FormatState & state, FormatStateStacked frame) const
{
if (!elem)
return;
if (prefix.empty())
{
elem->format(ostr, s, state, frame);
return;
}
ostr << prefix << ' ';
elem->format(ostr, s, state, frame);
}
ASTPtr ASTColumns::clone() const
{
auto res = make_intrusive<ASTColumns>();
if (columns)
res->set(res->columns, columns->clone());
if (indices)
res->set(res->indices, indices->clone());
if (constraints)
res->set(res->constraints, constraints->clone());
if (projections)
res->set(res->projections, projections->clone());
if (primary_key)
res->set(res->primary_key, primary_key->clone());
if (primary_key_from_columns)
res->set(res->primary_key_from_columns, primary_key_from_columns->clone());
return res;
}
void ASTColumns::formatImpl(WriteBuffer & ostr, const FormatSettings & s, FormatState & state, FormatStateStacked frame) const
{
ASTExpressionList list;
if (columns)
{
for (const auto & column : columns->children)
{
auto elem = make_intrusive<ASTColumnsElement>();
elem->prefix = "";
elem->set(elem->elem, column->clone());
list.children.push_back(elem);
}
}
if (indices)
{
for (const auto & index : indices->children)
{
auto elem = make_intrusive<ASTColumnsElement>();
elem->prefix = "INDEX";
elem->set(elem->elem, index->clone());
list.children.push_back(elem);
}
}
if (constraints)
{
for (const auto & constraint : constraints->children)
{
auto elem = make_intrusive<ASTColumnsElement>();
elem->prefix = "CONSTRAINT";
elem->set(elem->elem, constraint->clone());
list.children.push_back(elem);
}
}
if (projections)
{
for (const auto & projection : projections->children)
{
auto elem = make_intrusive<ASTColumnsElement>();
elem->prefix = "PROJECTION";
elem->set(elem->elem, projection->clone());
list.children.push_back(elem);
}
}
if (!list.children.empty())
{
if (s.one_line)
list.format(ostr, s, state, frame);
else
list.formatImplMultiline(ostr, s, state, frame);
}
}
ASTPtr ASTCreateQuery::clone() const
{
auto res = make_intrusive<ASTCreateQuery>(*this);
res->children.clear();
if (columns_list)
res->set(res->columns_list, columns_list->clone());
if (aliases_list)
res->set(res->aliases_list, aliases_list->clone());
if (storage)
res->set(res->storage, storage->clone());
if (select)
res->set(res->select, select->clone());
if (table_overrides)
res->set(res->table_overrides, table_overrides->clone());
if (targets)
res->set(res->targets, targets->clone());
if (sql_security)
res->set(res->sql_security, sql_security->clone());
if (watermark_function)
res->set(res->watermark_function, watermark_function->clone());
if (lateness_function)
res->set(res->lateness_function, lateness_function->clone());
if (dictionary)
{
chassert(is_dictionary);
res->set(res->dictionary_attributes_list, dictionary_attributes_list->clone());
res->set(res->dictionary, dictionary->clone());
}
if (refresh_strategy)
res->set(res->refresh_strategy, refresh_strategy->clone());
if (as_table_function)
res->set(res->as_table_function, as_table_function->clone());
if (comment)
res->set(res->comment, comment->clone());
cloneOutputOptions(*res);
cloneTableOptions(*res);
return res;
}
String ASTCreateQuery::getID(char delim) const
{
String res = attach ? "AttachQuery" : "CreateQuery";
String database = getDatabase();
if (!database.empty())
res += (delim + getDatabase());
res += (delim + getTable());
return res;
}
void ASTCreateQuery::writeJSON(WriteBuffer & out) const
{
JSONObjectWriter w(out, "CreateQuery");
w.writeString("database", getDatabase());
w.writeString("table", getTable());
/// Preserve the full `database`/`table` ASTs so parameterized targets like `{tbl:Identifier}`
/// (whose `getTable()` is empty) survive the round-trip. The string form above is kept for
/// backward compatibility and readability; the AST form takes precedence on read.
w.writeChild("database_ast", database);
w.writeChild("table_ast", table);
if (isTemporary())
w.writeBool("is_temporary", true);
if (!cluster.empty())
w.writeString("cluster", cluster);
if (!as_database.empty())
w.writeString("as_database", as_database);
if (!as_table.empty())
w.writeString("as_table", as_table);
if (!attach_from_path.empty())
w.writeString("attach_from_path", attach_from_path);
w.writeBool("attach", attach);
w.writeBool("if_not_exists", if_not_exists);
w.writeBool("is_ordinary_view", is_ordinary_view);
w.writeBool("is_materialized_view", is_materialized_view);
w.writeBool("is_window_view", is_window_view);
w.writeBool("is_time_series_table", is_time_series_table);
w.writeBool("is_populate", is_populate);
w.writeBool("is_create_empty", is_create_empty);
w.writeBool("is_clone_as", is_clone_as);
w.writeBool("replace_view", replace_view);
w.writeBool("has_uuid", has_uuid);
w.writeBool("has_uuid_clause", has_uuid_clause);
w.writeBool("has_inner_uuid_clause", has_inner_uuid_clause);
if (uuid != UUIDHelpers::Nil)
w.writeString("uuid", toString(uuid));
w.writeBool("is_dictionary", is_dictionary);
w.writeBool("is_watermark_strictly_ascending", is_watermark_strictly_ascending);
w.writeBool("is_watermark_ascending", is_watermark_ascending);
w.writeBool("is_watermark_bounded", is_watermark_bounded);
w.writeBool("allowed_lateness", allowed_lateness);
w.writeBool("attach_short_syntax", attach_short_syntax);
w.writeBool("replace_table", replace_table);
w.writeBool("create_or_replace", create_or_replace);
w.writeBool("has_attach_from_path", has_attach_from_path);
if (attach_as_replicated.has_value())
w.writeBool("attach_as_replicated", *attach_as_replicated);
w.writeChild("columns_list", columns_list);
w.writeChild("aliases_list", aliases_list);
w.writeChild("storage", storage);
w.writeChild("watermark_function", watermark_function);
w.writeChild("lateness_function", lateness_function);
w.writeChild("as_table_function", as_table_function);
w.writeChild("select", select);
w.writeChild("targets", targets);
w.writeChild("comment", comment);
w.writeChild("sql_security", sql_security);
w.writeChild("table_overrides", table_overrides);
w.writeChild("dictionary_attributes_list", dictionary_attributes_list);
w.writeChild("dictionary", dictionary);
w.writeChild("refresh_strategy", refresh_strategy);
writeOutputOptionsJSON(w);
}
void ASTCreateQuery::readJSON(const Poco::JSON::Object & json)
{
JSONObjectReader r(json);
String db = r.getString("database");
if (!db.empty())
setDatabase(db);
String tbl = r.getString("table");
if (!tbl.empty())
setTable(tbl);
/// The full ASTs take precedence over the string form: parameterized targets like
/// `{tbl:Identifier}` have an empty `getTable()` and can only be restored from the AST.
/// `setOrReplace` keeps `children` consistent regardless of whether the string form above
/// already populated the member. These slots are parser-produced identifiers;
/// `getDatabase`/`getTable` read them via `tryGetIdentifierNameInto`, so reject other node
/// types here.
if (auto database_ast = r.readIdentifierChild("database_ast"))
setOrReplace(database, database_ast);
if (auto table_ast = r.readIdentifierChild("table_ast"))
setOrReplace(table, table_ast);
if (r.getBool("is_temporary"))
setIsTemporary(true);
cluster = r.getString("cluster");
as_database = r.getString("as_database");
as_table = r.getString("as_table");
attach_from_path = r.getString("attach_from_path");
attach = r.getBool("attach");
if_not_exists = r.getBool("if_not_exists");
is_ordinary_view = r.getBool("is_ordinary_view");
is_materialized_view = r.getBool("is_materialized_view");
is_window_view = r.getBool("is_window_view");
is_time_series_table = r.getBool("is_time_series_table");
is_populate = r.getBool("is_populate");
is_create_empty = r.getBool("is_create_empty");
is_clone_as = r.getBool("is_clone_as");
replace_view = r.getBool("replace_view");
has_uuid = r.getBool("has_uuid");
has_uuid_clause = r.getBool("has_uuid_clause");
has_inner_uuid_clause = r.getBool("has_inner_uuid_clause");
if (r.has("uuid"))
uuid = parseFromString<UUID>(r.getString("uuid"));
is_dictionary = r.getBool("is_dictionary");
is_watermark_strictly_ascending = r.getBool("is_watermark_strictly_ascending");
is_watermark_ascending = r.getBool("is_watermark_ascending");
is_watermark_bounded = r.getBool("is_watermark_bounded");
allowed_lateness = r.getBool("allowed_lateness");
attach_short_syntax = r.getBool("attach_short_syntax");
replace_table = r.getBool("replace_table");
create_or_replace = r.getBool("create_or_replace");
has_attach_from_path = r.getBool("has_attach_from_path");
if (r.has("attach_as_replicated"))
attach_as_replicated = r.getBool("attach_as_replicated");
/// `attach_short_syntax`, `has_attach_from_path` / `attach_from_path`, and `attach_as_replicated`
/// are produced only for `ATTACH TABLE` forms: the parser gates the `FROM '<path>'` and
/// `AS [NOT] REPLICATED` clauses behind `attach`, and `attach_short_syntax` is set only when the
/// interpreter re-attaches a detached table. Reject them from non-`ATTACH` JSON so `clickhouse_json`
/// cannot build a parser-impossible `CREATE TABLE` whose formatting hides attach-only state that
/// `InterpreterCreateQuery` still consumes (and which would also trip the `attach || !has_attach_from_path`
/// assertion in `formatImpl`).
if (!attach)
{
if (attach_short_syntax)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"'attach_short_syntax' is only valid for ATTACH queries during AST JSON deserialization");
if (has_attach_from_path || !attach_from_path.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"'attach_from_path' / 'has_attach_from_path' are only valid for ATTACH queries during AST JSON deserialization");
if (attach_as_replicated.has_value())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"'attach_as_replicated' is only valid for ATTACH queries during AST JSON deserialization");
}
/// The path and its presence flag always travel together (the parser sets both, and `formatImpl`
/// emits ` FROM <attach_from_path>` whenever `has_attach_from_path` is set), so reject any payload
/// that carries one without the other.
if (has_attach_from_path != !attach_from_path.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"'has_attach_from_path' must match whether a non-empty 'attach_from_path' is present during AST JSON deserialization");
/// `has_uuid` is not an independent parser input: every SQL parser path derives it from
/// `uuid != Nil`. Reject JSON that sets it inconsistently with the restored `uuid`, otherwise a
/// payload with `"has_uuid": true` and no `uuid` would enable `{uuid}` macro expansion
/// (see `TableZnodeInfo::resolve` / `DatabaseReplicated`) while `formatQueryFromJSON` shows no
/// `UUID` clause.
if (has_uuid != (uuid != UUIDHelpers::Nil))
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"'has_uuid' must match whether a non-Nil 'uuid' is present during AST JSON deserialization");
/// Restore concrete-typed members with `readChildOfType` so a wrong node type from malformed
/// `clickhouse_json` is rejected with `BAD_ARGUMENTS` here, instead of reaching `set` as a
/// `LOGICAL_ERROR` cast failure (or, for `sql_security`, a downstream `as<ASTSQLSecurity>`
/// invariant violation). The `*_function` and `comment` slots hold arbitrary expressions.
auto child = r.readChildOfType<ASTColumns>("columns_list");
if (child)
set(columns_list, child);
child = r.readChildOfType<ASTExpressionList>("aliases_list");
if (child)
{
/// `aliases_list` is parser-produced as an `ASTExpressionList` of `ASTIdentifier`
/// (`ParserAliasesExpressionList`); `InterpreterCreateQuery` later does
/// `aliases_children[i]->as<ASTIdentifier &>()` when applying view column aliases,
/// so validate the children too, not just the outer list type.
for (const auto & alias : child->children)
if (!alias || !alias->as<ASTIdentifier>())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"View column aliases in 'aliases_list' must be identifiers during AST JSON deserialization");
set(aliases_list, child);
}
child = r.readChildOfType<ASTStorage>("storage");
if (child)
set(storage, child);
child = r.readChild("watermark_function");
if (child)
set(watermark_function, child);
child = r.readChild("lateness_function");
if (child)
set(lateness_function, child);
/// `as_table_function` is parser-produced as an `ASTFunction` (`AS table_function(...)`);
/// `InterpreterCreateQuery::setEngine` does `as_table_function->as<ASTFunction>()->name`.
child = r.readChildOfType<ASTFunction>("as_table_function");
if (child)
set(as_table_function, child);
child = r.readChildOfType<ASTSelectWithUnionQuery>("select");
if (child)
set(select, child);
child = r.readChildOfType<ASTViewTargets>("targets");
if (child)
set(targets, child);
/// `comment` is parsed by `ParserStringLiteral`; `StorageFactory::get`/`DatabaseFactory::get`
/// read `comment->as<ASTLiteral &>().value.safeGet<String>()`, so require a string literal here.
child = r.readStringLiteralChild("comment");
if (child)
set(comment, child);
child = r.readChildOfType<ASTSQLSecurity>("sql_security");
if (child)
{
/// `formatImpl` emits `sql_security` only for view shapes (`supportSQLSecurity()`), but
/// `InterpreterCreateQuery::createTable` runs `processSQLSecurityOption` for any non-null
/// `sql_security`. Reject it on non-view shapes (e.g. a plain `CREATE TABLE`) so the formatted
/// SQL cannot hide a definer clause that execution still enforces.
if (!supportSQLSecurity())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"`sql_security` is only valid for VIEW / MATERIALIZED VIEW during AST JSON deserialization");
set(sql_security, child);
}
child = r.readChildOfType<ASTTableOverrideList>("table_overrides");
if (child)
set(table_overrides, child);
child = r.readChildOfType<ASTExpressionList>("dictionary_attributes_list");
if (child)
{
/// Dictionary configuration walks this list and downcasts each child to
/// `ASTDictionaryAttributeDeclaration` (the only type `ParserDictionaryAttributeDeclarationList` produces).
for (const auto & attribute : child->children)
if (!attribute || !attribute->as<ASTDictionaryAttributeDeclaration>())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"'dictionary_attributes_list' must contain only dictionary attribute declarations during AST JSON deserialization");
set(dictionary_attributes_list, child);
}
child = r.readChildOfType<ASTDictionary>("dictionary");
if (child)
set(dictionary, child);
child = r.readChildOfType<ASTRefreshStrategy>("refresh_strategy");
if (child)
set(refresh_strategy, child);
/// `formatQueryImpl` only enters the `CREATE DATABASE` branch when `database` is set and `table` is unset.
/// All other forms (`TABLE`, `VIEW`, `MATERIALIZED VIEW`, `WINDOW VIEW`, `DICTIONARY`, ...) require `table`;
/// otherwise we fall into a `chassert(table); table->format(...)` path that null-derefs in release builds.
/// Without form-shape validation, JSON such as `{"database":"db","is_ordinary_view":true}` would silently
/// format as `CREATE DATABASE db`, dropping the view-specific flags instead of being rejected.
if (!table && !database)
throw Exception(ErrorCodes::BAD_ARGUMENTS, "`CreateQuery` must specify at least one of 'database' or 'table' during AST JSON deserialization");
const bool requires_table =
is_ordinary_view || is_materialized_view || is_window_view
|| is_dictionary || is_time_series_table
|| is_populate || is_create_empty || is_clone_as
|| replace_view || replace_table || create_or_replace
|| has_attach_from_path || attach_as_replicated.has_value()
|| allowed_lateness
|| is_watermark_strictly_ascending || is_watermark_ascending || is_watermark_bounded
|| columns_list || aliases_list || select
|| watermark_function || lateness_function || as_table_function
|| targets || sql_security
|| dictionary_attributes_list || dictionary || refresh_strategy
|| !as_table.empty() || !attach_from_path.empty();
if (requires_table && !table)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"`CreateQuery` is missing 'table' during AST JSON deserialization, but the surrounding flags indicate a non-database form");
/// The parser attaches each of these clause families only to specific `CREATE` variants:
/// `refresh_strategy` only to materialized views; the watermark strategies and `ALLOWED LATENESS`
/// only to window views; `targets` (`ASTViewTargets`) to materialized views (`TO`/`TO INNER UUID`),
/// window views (`TO`/inner engine), `TimeSeries` tables (`DATA`/`TAGS`/`METRICS`) and plain tables
/// with an explicit `TO INNER UUID` clause (`SharedSet`/`SharedJoin`). Malformed `clickhouse_json`
/// could attach them to other variants; `formatQueryImpl` would then emit SQL the parser never
/// accepts (e.g. `CREATE TABLE t REFRESH ...` or `CREATE TABLE t TO dst ...`) while execution
/// still partially consumes the hidden state. Reject such shapes instead.
if (refresh_strategy && !is_materialized_view)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"`CreateQuery` has 'refresh_strategy' set but is not a materialized view during AST JSON deserialization");
if ((is_watermark_strictly_ascending || is_watermark_ascending || is_watermark_bounded) && !is_window_view)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"`CreateQuery` has a watermark strategy set but is not a window view during AST JSON deserialization");
if (allowed_lateness && !is_window_view)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"`CreateQuery` has 'allowed_lateness' set but is not a window view during AST JSON deserialization");
if (targets && !is_materialized_view && !is_window_view && !is_time_series_table)
{
/// The only non-view / non-`TimeSeries` form that carries `targets` is a plain table with a
/// `TO INNER UUID` clause. `ParserCreateQuery` builds it only for `SharedSet`/`SharedJoin` engines
/// (see `to_inner_uuid` handling in `ParserCreateQuery.cpp`), and the resulting `ASTViewTargets`
/// holds exactly one `To` target whose sole payload is `inner_uuid` — no external table name, no
/// inner engine, no inner columns, and no other target kinds. Merely honouring `has_inner_uuid_clause`
/// is not enough: any other `targets` shape (an external `TO dst` table, `ENGINE`/`SAMPLES`/`TAGS`
/// targets, or a non-`SharedSet`/`SharedJoin` engine) makes `formatQueryImpl` emit SQL such as
/// `CREATE TABLE t TO dst ...` that the SQL parser never accepts. Require the flag, the exact target
/// shape, and the matching engine.
if (!has_inner_uuid_clause)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"`CreateQuery` has 'targets' set but is not a materialized view, window view, `TimeSeries` table, "
"or a table with a 'TO INNER UUID' clause during AST JSON deserialization");
const auto & view_targets = targets->as<const ASTViewTargets &>();
const bool valid_inner_uuid_shape =
view_targets.targets.size() == 1
&& view_targets.targets[0].kind == ViewTarget::To
&& view_targets.targets[0].inner_uuid != UUIDHelpers::Nil
&& view_targets.targets[0].table_id.empty()
&& !view_targets.targets[0].inner_engine
&& !view_targets.targets[0].inner_columns
&& !view_targets.targets[0].table_ast;
if (!valid_inner_uuid_shape)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"`CreateQuery` with a 'TO INNER UUID' clause on a plain table must carry exactly one inner-UUID "
"'TO' target and nothing else during AST JSON deserialization");
const bool inner_uuid_engine =
storage && storage->engine
&& (storage->engine->name == "SharedSet" || storage->engine->name == "SharedJoin");
if (!inner_uuid_engine)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"`CreateQuery` with a 'TO INNER UUID' clause is only valid for the `SharedSet` / `SharedJoin` "
"engines during AST JSON deserialization");
}
/// `formatQueryImpl` unconditionally dereferences `lateness_function` when `allowed_lateness` is set,
/// and `watermark_function` when the bounded watermark strategy is selected. Without the child
/// expression present, formatting would null-deref. Reject such inconsistent JSON up front.
if (allowed_lateness && !lateness_function)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"`CreateQuery` has 'allowed_lateness' set but is missing 'lateness_function' during AST JSON deserialization");
/// `formatQueryImpl` treats the watermark strategy as a single choice using an if/else-if chain over
/// `is_watermark_strictly_ascending`, `is_watermark_ascending` and `is_watermark_bounded`. The SQL parser
/// can only ever set one of them. Malformed JSON could set several at once, which would silently drop the
/// lower-priority modes on format; reject it instead of rewriting it.
const size_t watermark_modes =
static_cast<size_t>(is_watermark_strictly_ascending)
+ static_cast<size_t>(is_watermark_ascending)
+ static_cast<size_t>(is_watermark_bounded);
if (watermark_modes > 1)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"`CreateQuery` sets more than one watermark strategy at once during AST JSON deserialization, "
"but they are mutually exclusive");
/// `is_ordinary_view`, `is_materialized_view`, `is_window_view` and `is_dictionary` are mutually
/// exclusive query kinds: the parser produces exactly one, and `formatQueryImpl` selects the form via
/// an `if (!is_dictionary)` / `if`-`else if` chain over the view flags. Setting several at once would
/// let formatting and execution disagree (e.g. both `is_ordinary_view` and `is_materialized_view`
/// formats as `CREATE VIEW` while `InterpreterCreateQuery` still runs materialized-view setup).
const size_t create_kinds =
static_cast<size_t>(is_ordinary_view)
+ static_cast<size_t>(is_materialized_view)
+ static_cast<size_t>(is_window_view)
+ static_cast<size_t>(is_dictionary);
if (create_kinds > 1)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"`CreateQuery` sets more than one of 'is_ordinary_view'/'is_materialized_view'/'is_window_view'/"
"'is_dictionary' during AST JSON deserialization, but they are mutually exclusive");
/// `watermark_function` is only meaningful for (and only formatted by) the bounded watermark strategy.
/// The parser attaches it exactly when the bounded mode is selected, so require it to be present iff
/// `is_watermark_bounded`. A missing function would null-deref in `formatQueryImpl`; a stray function
/// in a non-bounded mode would be silently ignored.
if (is_watermark_bounded && !watermark_function)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"`CreateQuery` has a bounded watermark strategy set but is missing 'watermark_function' during AST JSON deserialization");
if (!is_watermark_bounded && watermark_function)
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"`CreateQuery` has 'watermark_function' set without a bounded watermark strategy during AST JSON deserialization");
readOutputOptionsJSON(r);
}
void ASTCreateQuery::formatQueryImpl(WriteBuffer & ostr, const FormatSettings & settings, FormatState & state, FormatStateStacked frame) const
{
if (database && !table)
{
ostr
<< (attach ? "ATTACH DATABASE " : "CREATE DATABASE ")
<< (if_not_exists ? "IF NOT EXISTS " : "");
database->format(ostr, settings, state, frame);
if (uuid != UUIDHelpers::Nil)
ostr << " UUID " << quoteString(toString(uuid));
formatOnCluster(ostr, settings);
if (storage)
storage->format(ostr, settings, state, frame);
if (table_overrides)
{
ostr << settings.nl_or_ws;
table_overrides->format(ostr, settings, state, frame);
}
if (comment)
{
ostr << settings.nl_or_ws << "COMMENT ";
comment->format(ostr, settings, state, frame);
}
return;
}
if (!is_dictionary)
{
String action = "CREATE";
if (attach)
action = "ATTACH";
else if (replace_view)
action = "CREATE OR REPLACE";
else if (replace_table && create_or_replace)
action = "CREATE OR REPLACE";
else if (replace_table)
action = "REPLACE";
String what = "TABLE";
if (is_ordinary_view)
what = "VIEW";
else if (is_materialized_view)
what = "MATERIALIZED VIEW";
else if (is_window_view)
what = "WINDOW VIEW";
ostr << action;
ostr << " ";
ostr << (isTemporary() ? "TEMPORARY " : "")
<< what << " "
<< (if_not_exists ? "IF NOT EXISTS " : "")
;
if (database)
{
database->format(ostr, settings, state, frame);
ostr << '.';
}
chassert(table);
table->format(ostr, settings, state, frame);
if (uuid != UUIDHelpers::Nil)
ostr << " UUID " << quoteString(toString(uuid));
chassert(attach || !has_attach_from_path);
if (has_attach_from_path)
ostr << " FROM " << quoteString(attach_from_path);
if (attach_as_replicated.has_value())
{
if (attach_as_replicated.value())
ostr << " AS REPLICATED";
else
ostr << " AS NOT REPLICATED";
}
formatOnCluster(ostr, settings);
}
else
{
String action = "CREATE";
if (attach)
action = "ATTACH";
else if (replace_table && create_or_replace)
action = "CREATE OR REPLACE";
else if (replace_table)
action = "REPLACE";
/// Always DICTIONARY
ostr << action << " DICTIONARY " << (if_not_exists ? "IF NOT EXISTS " : "");
if (database)
{
database->format(ostr, settings, state, frame);
ostr << '.';
}
chassert(table);
table->format(ostr, settings, state, frame);
if (uuid != UUIDHelpers::Nil)
ostr << " UUID " << quoteString(toString(uuid));
formatOnCluster(ostr, settings);
}
if (refresh_strategy)
{
ostr << settings.nl_or_ws;
refresh_strategy->format(ostr, settings, state, frame);
}
if (auto to_table_id = getTargetTableID(ViewTarget::To))
{
ostr << " " << toStringView(Keyword::TO)
<< " "
<< (!to_table_id.database_name.empty() ? backQuoteIfNeed(to_table_id.database_name) + "." : "")
<< backQuoteIfNeed(to_table_id.table_name);
}
else if (targets && targets->hasTableASTWithQueryParams(ViewTarget::To))
{
auto to_table_ast = targets->getTableASTWithQueryParams(ViewTarget::To);
chassert(to_table_ast);
ostr << " " << toStringView(Keyword::TO) << " ";
to_table_ast->format(ostr, settings, state, frame);
}
if (auto to_inner_uuid = getTargetInnerUUID(ViewTarget::To); to_inner_uuid != UUIDHelpers::Nil)
{
ostr << " " << toStringView(Keyword::TO_INNER_UUID)
<< " " << quoteString(toString(to_inner_uuid));
}
bool should_add_empty = is_create_empty;
auto add_empty_if_needed = [&]
{
if (!should_add_empty)
return;
should_add_empty = false;
ostr << " EMPTY";
};
bool should_add_clone = is_clone_as;
auto add_clone_if_needed = [&]
{
if (!should_add_clone)
return;
should_add_clone = false;
ostr << " CLONE";
};
if (!as_table.empty())
{
add_empty_if_needed();
add_clone_if_needed();
ostr
<< " AS "
<< (!as_database.empty() ? backQuoteIfNeed(as_database) + "." : "") << backQuoteIfNeed(as_table);
}
if (as_table_function)
{
if (columns_list && !columns_list->empty())
{
frame.expression_list_always_start_on_new_line = true;
ostr << (settings.one_line ? " (" : "\n(");
columns_list->format(ostr, settings, state, frame);
ostr << (settings.one_line ? ")" : "\n)");
frame.expression_list_always_start_on_new_line = false;
}
add_empty_if_needed();