Repository navigation
Expand file tree
/
Copy pathexecuteQuery.cpp
More file actions
5492 lines (4874 loc) · 276 KB
/
Copy pathexecuteQuery.cpp
File metadata and controls
5492 lines (4874 loc) · 276 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/DateLUTImpl.h>
#include <Common/CurrentMetrics.h>
#include <Common/CurrentThread.h>
#include <Common/ThreadStatus.h>
#include <Common/ThreadGroupSwitcher.h>
#include <Common/Logger.h>
#include <Common/saturatedDuration.h>
#include <Common/StringUtils.h>
#include <Common/logger_useful.h>
#include <Common/Exception.h>
#include <Common/formatReadable.h>
#include <Common/PODArray.h>
#include <Common/typeid_cast.h>
#include <Common/thread_local_rng.h>
#include <Common/SensitiveDataMasker.h>
#include <Common/FailPoint.h>
#include <Common/LockMemoryExceptionInThread.h>
#include <Common/FieldVisitorToString.h>
#include <Common/SignalHandlers.h>
#include <Common/Stopwatch.h>
#include <Common/scope_guard_safe.h>
#include <Interpreters/normalizeDivision.h>
#include <Interpreters/AsynchronousInsertQueue.h>
#include <Interpreters/Cache/QueryResultCache.h>
#include <Interpreters/Cache/QueryResultCacheOnDisk.h>
#include <IO/WriteBufferFromVector.h>
#include <IO/LimitReadBuffer.h>
#include <IO/ReadBuffer.h>
#include <IO/MemoryReadWriteBuffer.h>
#include <IO/copyData.h>
#include <Processors/ProcessorsProfileLogInfo.h>
#include <QueryPipeline/BlockIO.h>
#include <Processors/Transforms/getSourceFromASTInsertQuery.h>
#include <Processors/Formats/Impl/NullFormat.h>
#include <Parsers/ASTBackupQuery.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTInsertQuery.h>
#include <Parsers/ASTSelectQuery.h>
#include <Parsers/ASTCreateQuery.h>
#include <Parsers/ASTAlterQuery.h>
#include <Parsers/ASTSelectWithUnionQuery.h>
#include <Parsers/ASTShowProcesslistQuery.h>
#include <Parsers/ASTTransactionControl.h>
#include <Parsers/ASTExplainQuery.h>
#include <Parsers/Access/ASTExecuteAsQuery.h>
#include <Parsers/ASTAsterisk.h>
#include <Parsers/ASTExpressionList.h>
#include <Parsers/ASTSubquery.h>
#include <Parsers/ASTTablesInSelectQuery.h>
#include <Parsers/ParserTablesInSelectQuery.h>
#include <Parsers/ExpressionListParsers.h>
#include <Parsers/parseQuery.h>
#include <Parsers/ASTFromJSON.h>
#include <Parsers/ParserQuery.h>
#include <Parsers/queryNormalization.h>
#include <Common/quoteString.h>
#include <Parsers/toOneLineQuery.h>
#include <Parsers/Kusto/parseKQLQuery.h>
#include <Parsers/PRQL/ParserPRQLQuery.h>
#include <Parsers/Polyglot/ParserPolyglotQuery.h>
#include <Parsers/Trino/ParserTrinoQuery.h>
#include <Parsers/Prometheus/ParserPrometheusQuery.h>
#include <Parsers/LogsQL/ParserLogsQLQuery.h>
#include <Parsers/LogsQL/parseLogsQLQuery.h>
#include <Formats/FormatFactory.h>
#include <Storages/StorageInput.h>
#include <Access/ContextAccess.h>
#include <Access/EnabledQuota.h>
#include <Interpreters/ApplyWithGlobalVisitor.h>
#include <Interpreters/Context.h>
#include <Interpreters/InterpreterFactory.h>
#include <Interpreters/InterpreterInsertQuery.h>
#include <Interpreters/InterpreterCreateQuery.h>
#include <Interpreters/InterpreterExplainQuery.h>
#include <Interpreters/InterpreterSelectQueryAnalyzer.h>
#include <Interpreters/InterpreterSetQuery.h>
#include <Interpreters/InterpreterTransactionControlQuery.h>
#include <Interpreters/NormalizeSelectWithUnionQueryVisitor.h>
#include <Interpreters/QueryConstructionSettings.h>
#include <Interpreters/ProcessList.h>
#include <Interpreters/ProcessorsProfileLog.h>
#include <Interpreters/QueryExecutionCounters.h>
#include <Processors/QueryPlan/Profiling/Capture/QueryPlanLogCapture.h>
#include <Processors/QueryPlan/Profiling/Render/FlatJSONPlanRenderer.h>
#include <Interpreters/QueryLog.h>
#include <Interpreters/SessionQueryIdsHistory.h>
#include <IO/AsyncReadCounters.h>
#include <Interpreters/QueryMetricLog.h>
#include <Interpreters/ReplaceQueryParameterVisitor.h>
#include <Interpreters/SelectIntersectExceptQueryVisitor.h>
#include <Interpreters/SelectQueryOptions.h>
#include <Interpreters/TransactionManager.h>
#include <Interpreters/executeQuery.h>
#include <Databases/IDatabase.h>
#include <Interpreters/DatabaseCatalog.h>
#include <Interpreters/QueryMetadataCache.h>
#include <Common/ProfileEvents.h>
#include <Common/ElapsedTimeProfileEventIncrement.h>
#include <Parsers/ASTSystemQuery.h>
#include <Parsers/stripQuerySettings.h>
#include <QueryPipeline/printPipeline.h>
#include <IO/Progress.h>
#include <Parsers/ASTIdentifier_fwd.h>
#if CLICKHOUSE_CLOUD
#include <Common/Licensing/LicenseChecker.h>
#endif
#include <Core/BaseSettings.h>
#include <Core/ServerSettings.h>
#include <Core/Settings.h>
#include <Core/SettingsFields.h>
#include <Core/SettingsEnums.h>
#include <Core/SettingsSecrets.h>
#include <IO/CompressionMethod.h>
#include <Processors/Formats/Framing/FramingFormatFactory.h>
#include <Processors/Formats/IOutputFormat.h>
#include <Processors/Executors/CompletedPipelineExecutor.h>
#include <Processors/Executors/PullingPipelineExecutor.h>
#include <Processors/Sources/WaitForAsyncInsertSource.h>
#include <Processors/QueryPlan/BuildQueryPipelineSettings.h>
#include <Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.h>
#include <Processors/QueryPlan/RuntimeFilterLookup.h>
#include <QueryPipeline/QueryPipelineBuilder.h>
#include <Common/QueryFuzzer.h>
#include <Interpreters/QueryOracleChecker.h>
#include <Common/randomSeed.h>
#include <Common/ThreadPool.h>
#include <base/getFQDNOrHostName.h>
#include <Interpreters/InternalTextLogsQueue.h>
#include <Interpreters/ProfileEventsExt.h>
#include <Poco/Logger.h>
#include <Poco/Net/SocketAddress.h>
#include <exception>
#include <memory>
#include <mutex>
#include <random>
#include <boost/algorithm/string/predicate.hpp>
namespace ProfileEvents
{
extern const Event Query;
extern const Event InsertQuery;
extern const Event FailedQuery;
extern const Event FailedInsertQuery;
extern const Event FailedSelectQuery;
extern const Event FailedInternalQuery;
extern const Event FailedInternalInsertQuery;
extern const Event FailedInternalSelectQuery;
extern const Event FailedInitialQuery;
extern const Event FailedInitialSelectQuery;
extern const Event QueryTimeMicroseconds;
extern const Event SelectQueryTimeMicroseconds;
extern const Event InsertQueryTimeMicroseconds;
extern const Event OtherQueryTimeMicroseconds;
extern const Event ASTFuzzerQueries;
extern const Event ASTFuzzerSkippedBackupRestore;
extern const Event ASTFuzzerSkippedReplicatedDDLInternal;
extern const Event ASTFuzzerSkippedCollaborativeWorker;
extern const Event ASTFuzzerSkippedSecondaryQuery;
extern const Event QueryParseMicroseconds;
}
namespace CurrentMetrics
{
extern const Metric IsServerShuttingDown;
}
namespace DB
{
namespace Setting
{
extern const SettingsBool allow_experimental_analyzer;
extern const SettingsBool enable_json_ast_dialect;
extern const SettingsBool enable_polyglot_dialect;
extern const SettingsBool enable_kusto_dialect;
extern const SettingsBool enable_prql_dialect;
extern const SettingsBool enable_trino_dialect;
extern const SettingsBool allow_settings_after_format_in_insert;
extern const SettingsBool ast_fuzzer_any_query;
extern const SettingsBool ast_fuzzer_oracle;
extern const SettingsFloat ast_fuzzer_runs;
extern const SettingsBool async_insert;
extern const SettingsBool calculate_text_stack_trace;
extern const SettingsBool deduplicate_blocks_in_dependent_materialized_views;
extern const SettingsDialect dialect;
extern const SettingsOverflowMode distinct_overflow_mode;
extern const SettingsBool enable_global_with_statement;
extern const SettingsBool enable_reads_from_query_cache;
extern const SettingsSetOperationMode except_default_mode;
extern const SettingsString framing_output_format;
extern const SettingsOverflowModeGroupBy group_by_overflow_mode;
extern const SettingsBool implicit_transaction;
extern const SettingsUInt64 interactive_delay;
extern const SettingsSetOperationMode intersect_default_mode;
extern const SettingsOverflowMode join_overflow_mode;
extern const SettingsString log_comment;
extern const SettingsBool log_formatted_queries;
extern const SettingsBool log_profile_events;
extern const SettingsUInt64 log_queries_cut_to_length;
extern const SettingsUInt64 log_query_plans_max_size;
extern const SettingsBool log_queries;
extern const SettingsMilliseconds log_queries_min_query_duration_ms;
extern const SettingsLogQueriesType log_queries_min_type;
extern const SettingsFloat log_queries_probability;
extern const SettingsBool log_query_settings;
extern const SettingsUInt64 max_ast_depth;
extern const SettingsUInt64 max_ast_elements;
extern const SettingsUInt64 max_expanded_ast_elements;
extern const SettingsNonZeroUInt64 max_block_size;
extern const SettingsUInt64 max_parser_backtracks;
extern const SettingsUInt64 max_parser_depth;
extern const SettingsUInt64 max_query_size;
extern const SettingsUInt64 output_format_compression_level;
extern const SettingsString polyglot_dialect;
extern const SettingsBool enable_logsql_dialect;
extern const SettingsString logsql_database;
extern const SettingsString logsql_table;
extern const SettingsString logsql_time_column;
extern const SettingsString logsql_message_column;
extern const SettingsUInt64 output_format_compression_zstd_window_log;
extern const SettingsBool query_cache_compress_entries;
extern const SettingsUInt64 query_cache_max_entries;
extern const SettingsUInt64 query_cache_max_size_in_bytes;
extern const SettingsMilliseconds query_cache_min_query_duration;
extern const SettingsUInt64 query_cache_min_query_runs;
extern const SettingsQueryResultCacheNondeterministicFunctionHandling query_cache_nondeterministic_function_handling;
extern const SettingsBool query_cache_share_between_users;
extern const SettingsBool query_cache_squash_partial_results;
extern const SettingsQueryResultCacheSystemTableHandling query_cache_system_table_handling;
extern const SettingsSeconds query_cache_ttl;
extern const SettingsInt64 query_metric_log_interval;
extern const SettingsOverflowMode read_overflow_mode;
extern const SettingsOverflowMode read_overflow_mode_leaf;
extern const SettingsOverflowMode result_overflow_mode;
extern const SettingsBool run_query_in_background;
extern const SettingsLogsLevel send_logs_level;
extern const SettingsString send_logs_source_regexp;
extern const SettingsBool send_profile_events;
extern const SettingsUInt64 session_query_ids_history_size;
extern const SettingsOverflowMode set_overflow_mode;
extern const SettingsOverflowMode sort_overflow_mode;
extern const SettingsBool throw_on_unsupported_query_inside_transaction;
extern const SettingsOverflowMode timeout_overflow_mode;
extern const SettingsOverflowMode transfer_overflow_mode;
extern const SettingsSetOperationMode union_default_mode;
extern const SettingsBool use_query_cache;
extern const SettingsBool wait_for_async_insert;
extern const SettingsSeconds wait_for_async_insert_timeout;
extern const SettingsBool implicit_select;
extern const SettingsBool enforce_strict_identifier_format;
extern const SettingsMap http_response_headers;
extern const SettingsBool apply_mutations_on_fly;
extern const SettingsFloat min_os_cpu_wait_time_ratio_to_throw;
extern const SettingsFloat max_os_cpu_wait_time_ratio_to_throw;
extern const SettingsBool enable_time_series_table;
extern const SettingsString promql_database;
extern const SettingsString promql_table;
extern const SettingsDoubleAuto promql_evaluation_time;
extern const SettingsBool enable_shared_storage_snapshot_in_query;
extern const SettingsBool ignore_format_null_for_explain;
extern const SettingsString format;
extern const SettingsString output_format;
extern const SettingsString database;
extern const SettingsString select;
extern const SettingsString order;
extern const SettingsString sort;
extern const SettingsString filter;
extern const SettingsString implicit_table_at_top_level;
extern const SettingsDouble page;
extern const SettingsDouble limit;
extern const SettingsDouble offset;
}
namespace ServerSetting
{
extern const ServerSettingsUInt64 os_cpu_busy_time_threshold;
}
namespace ErrorCodes
{
extern const int QUERY_CACHE_USED_WITH_NON_THROW_OVERFLOW_MODE;
extern const int INTO_OUTFILE_NOT_ALLOWED;
extern const int INVALID_TRANSACTION;
extern const int LOGICAL_ERROR;
extern const int AST_FUZZER_ORACLE_MISMATCH;
extern const int NOT_IMPLEMENTED;
extern const int QUERY_WAS_CANCELLED;
extern const int QUERY_WAS_CANCELLED_BY_CLIENT;
extern const int SYNTAX_ERROR;
extern const int SUPPORT_IS_DISABLED;
extern const int BAD_ARGUMENTS;
extern const int ABORTED;
extern const int FAULT_INJECTED;
extern const int QUERY_IS_PROHIBITED;
}
namespace FailPoints
{
extern const char execute_query_calling_empty_set_result_func_on_exception[];
extern const char framing_finalize_throw[];
extern const char framing_throw_after_final_progress[];
extern const char terminate_with_exception[];
extern const char terminate_with_std_exception[];
extern const char libcxx_hardening_out_of_bounds_assertion[];
extern const char trigger_sanitizer_error[];
extern const char segfault_read_access[];
extern const char segfault_write_access[];
}
static TSA_NO_THREAD_SAFETY_ANALYSIS void triggerSanitizerError()
{
#if defined(ADDRESS_SANITIZER)
const auto data = std::make_unique_for_overwrite<char[]>(16);
[[maybe_unused]] volatile char c = data[16];
#elif defined(THREAD_SANITIZER)
std::mutex mutex;
mutex.unlock();
#elif defined(MEMORY_SANITIZER)
const auto data = std::make_unique_for_overwrite<char[]>(16);
if (data[7] == 42)
__builtin_trap();
#endif
}
static void checkASTSizeLimits(const IAST & ast, const Settings & settings)
{
if (settings[Setting::max_ast_depth])
ast.checkDepth(settings[Setting::max_ast_depth]);
if (settings[Setting::max_ast_elements])
ast.checkSize(settings[Setting::max_ast_elements]);
}
/// Log query into text log (not into system table).
static void logQuery(const String & query, ContextPtr context, bool internal, QueryProcessingStage::Enum stage)
{
if (internal)
{
LOG_DEBUG(getLogger("executeQuery"), "(internal) {} (stage: {})", toOneLineQuery(query), QueryProcessingStage::toString(stage));
}
else
{
const auto & client_info = context->getClientInfo();
const auto & current_query_id = client_info.current_query_id;
const auto & initial_query_id = client_info.initial_query_id;
const auto & current_user = client_info.current_user;
String comment = context->getSettingsRef()[Setting::log_comment];
size_t max_query_size = context->getSettingsRef()[Setting::max_query_size];
if (comment.size() > max_query_size)
comment.resize(max_query_size);
if (!comment.empty())
comment = fmt::format(" (comment: {})", comment);
String line_info;
if (client_info.script_line_number)
line_info = fmt::format(" (query {}, line {})", client_info.script_query_number, client_info.script_line_number);
String transaction_info;
if (auto txn = context->getCurrentTransaction())
transaction_info = fmt::format(" (TID: {}, TIDH: {})", txn->tid, txn->tid.getHash());
LOG_DEBUG(getLogger("executeQuery"), "(from {}{}{}){}{}{} {} (stage: {})",
client_info.current_address->toString(),
(current_user != "default" ? ", user: " + current_user : ""),
(!initial_query_id.empty() && current_query_id != initial_query_id ? ", initial_query_id: " + initial_query_id : std::string()),
transaction_info,
comment,
line_info,
toOneLineQuery(query),
QueryProcessingStage::toString(stage));
if (client_info.client_trace_context.trace_id != UUID())
{
LOG_TRACE(getLogger("executeQuery"),
"OpenTelemetry traceparent '{}'",
client_info.client_trace_context.composeTraceparentHeader());
}
}
}
/// Mirrors `LOG_IMPL`'s enablement check: a log file, the console and `system.text_log` all sit behind
/// the logger's own level, and a client can additionally ask for server logs through `send_logs_level`.
static bool errorMessageWillBeLogged(const LoggerPtr & logger)
{
/// `currentThreadHasGroup` must stay first: `currentThreadLogsLevel` throws without a thread status.
return (currentThreadHasGroup() && currentThreadLogsLevel() >= LogsLevel::error)
|| logger->is(Poco::Message::PRIO_ERROR);
}
/// Log exception (with query info) into text log (not into system table).
static void logException(ContextPtr context, QueryLogElement & elem, bool log_error = true)
{
String comment;
if (!elem.log_comment.empty())
comment = fmt::format(" (comment: {})", elem.log_comment);
/// Message patterns like "{} (from {}){} (in query: {})" are not really informative,
/// so we pass elem.exception_format_string as format string instead.
PreformattedMessage message;
message.format_string = elem.exception_format_string;
message.format_string_args = elem.exception_format_string_args;
const auto & client_info = context->getClientInfo();
String line_info;
if (client_info.script_line_number)
line_info = fmt::format(" (query {}, line {})", client_info.script_query_number, client_info.script_line_number);
if (elem.stack_trace.empty() || !log_error)
message.text = fmt::format("{} (from {}){}{} (in query: {})", elem.exception,
context->getClientInfo().current_address->toString(),
comment,
line_info,
toOneLineQuery(elem.query));
else
message.text = fmt::format(
"{} (from {}){}{} (in query: {}), Stack trace (when copying this message, always include the lines below):\n\n{}",
elem.exception,
context->getClientInfo().current_address->toString(),
comment,
line_info,
toOneLineQuery(elem.query),
elem.stack_trace);
if (log_error)
LOG_ERROR(getLogger("executeQuery"), message);
else
LOG_INFO(getLogger("executeQuery"), message);
}
static void
addPrivilegesInfoToQueryLogElement(QueryLogElement & element, const ContextPtr context_ptr)
{
const auto & privileges_info = context_ptr->getQueryPrivilegesInfo();
{
std::lock_guard lock(privileges_info.mutex);
element.used_privileges = privileges_info.used_privileges;
element.missing_privileges = privileges_info.missing_privileges;
}
}
/// The time-based event of the kind of the query, which is incremented along with `QueryTimeMicroseconds`.
static ProfileEvents::Event queryKindTimeEvent(const ASTPtr & query_ast)
{
if (!query_ast || query_ast->as<ASTSelectQuery>() || query_ast->as<ASTSelectWithUnionQuery>())
return ProfileEvents::SelectQueryTimeMicroseconds;
if (query_ast->as<ASTInsertQuery>())
return ProfileEvents::InsertQueryTimeMicroseconds;
return ProfileEvents::OtherQueryTimeMicroseconds;
}
static void
addStatusInfoToQueryLogElement(QueryLogElement & element, const QueryStatusInfo & info, const ASTPtr query_ast, const ContextPtr context_ptr, std::chrono::system_clock::time_point time)
{
UInt64 elapsed_microseconds = info.elapsed_microseconds;
element.event_time = timeInSeconds(time);
element.event_time_microseconds = timeInMicroseconds(time);
element.query_duration_ms = elapsed_microseconds / 1000;
ProfileEvents::increment(ProfileEvents::QueryTimeMicroseconds, elapsed_microseconds);
ProfileEvents::increment(queryKindTimeEvent(query_ast), elapsed_microseconds);
element.read_rows = info.read_rows;
element.read_bytes = info.read_bytes;
element.written_rows = info.written_rows;
element.written_bytes = info.written_bytes;
element.memory_usage = info.peak_memory_usage > 0 ? info.peak_memory_usage : 0;
element.thread_ids = info.thread_ids;
element.peak_threads_usage = info.peak_threads_usage;
if (info.profile_counters)
element.profile_counters = *info.profile_counters;
/// We need to refresh the access info since dependent views might have added extra information, either during
/// creation of the view (PushingToViews chain) or while executing its internal SELECT
const auto & access_info = context_ptr->getQueryAccessInfo();
{
std::lock_guard lock(access_info.mutex);
element.query_databases.insert(access_info.databases.begin(), access_info.databases.end());
element.query_tables.insert(access_info.tables.begin(), access_info.tables.end());
element.query_columns.insert(access_info.columns.begin(), access_info.columns.end());
element.query_partitions.insert(access_info.partitions.begin(), access_info.partitions.end());
element.query_projections.insert(access_info.projections.begin(), access_info.projections.end());
element.used_data_skipping_indices.insert(access_info.data_skipping_indices.begin(), access_info.data_skipping_indices.end());
element.query_views.insert(access_info.views.begin(), access_info.views.end());
element.used_row_policies.insert(access_info.row_policies.begin(), access_info.row_policies.end());
}
/// We copy QueryFactoriesInfo for thread-safety, because it is possible that query context can be modified by some processor even
/// after query is finished
const auto & factories_info(context_ptr->getQueryFactoriesInfo());
{
std::lock_guard lock(factories_info.mutex);
element.used_aggregate_functions = factories_info.aggregate_functions;
element.used_aggregate_function_combinators = factories_info.aggregate_function_combinators;
element.used_database_engines = factories_info.database_engines;
element.used_data_type_families = factories_info.data_type_families;
element.used_dictionaries = factories_info.dictionaries;
element.used_formats = factories_info.formats;
element.used_functions = factories_info.functions;
element.used_storages = factories_info.storages;
element.used_table_functions = factories_info.table_functions;
element.used_executable_user_defined_functions = factories_info.executable_user_defined_functions;
element.used_sql_user_defined_functions = factories_info.sql_user_defined_functions;
}
if (auto async_read_counters = context_ptr->getAsyncReadCounters())
{
auto add_counter = [&](const char * name, size_t value)
{
if (value)
element.async_read_counters.emplace(name, value);
};
add_counter("max_parallel_read_tasks", async_read_counters->max_parallel_read_tasks.load(std::memory_order_relaxed));
add_counter("max_parallel_prefetch_tasks", async_read_counters->max_parallel_prefetch_tasks.load(std::memory_order_relaxed));
add_counter("total_prefetch_tasks", async_read_counters->total_prefetch_tasks.load(std::memory_order_relaxed));
}
if (auto query_execution_counters = context_ptr->getQueryExecutionCounters())
{
auto counters = query_execution_counters->getSnapshot();
element.used_number_of_joins = counters.number_of_joins;
element.used_join_algorithms = std::move(counters.join_algorithms);
element.used_join_kinds = std::move(counters.join_kinds);
element.used_join_strictness = std::move(counters.join_strictness);
element.spilled_to_disk = std::move(counters.spilled_to_disk);
}
addPrivilegesInfoToQueryLogElement(element, context_ptr);
}
static UInt64 getQueryMetricLogInterval(ContextPtr context)
{
const auto & settings = context->getSettingsRef();
auto interval_milliseconds = settings[Setting::query_metric_log_interval];
if (interval_milliseconds < 0)
interval_milliseconds = context->getConfigRef().getUInt64("query_metric_log.collect_interval_milliseconds", 1000);
return interval_milliseconds;
}
/// The HTTP request URL is persisted to the query_log without its query string and fragment,
/// so that potentially sensitive request parameters (e.g. a `password` parameter or raw query
/// text) are never stored in the logs. The full URL remains available at runtime via
/// `currentRequestURL()`.
static String httpRequestURLForLogging(const ContextPtr & context)
{
const String & url = context->getHTTPRequestURL();
return String(stripQueryAndFragment(url));
}
String formatQueryForLogging(const String & query, const Settings & settings)
{
const char * pos = query.data();
const char * end = pos + query.size();
ParserQuery parser(end, settings[Setting::allow_settings_after_format_in_insert], settings[Setting::implicit_select]);
String parse_error;
const ASTPtr ast = tryParseQuery(
parser,
pos,
end,
parse_error,
/*hilite*/ false,
"",
/*allow_multi_statements*/ false,
settings[Setting::max_query_size],
settings[Setting::max_parser_depth],
settings[Setting::max_parser_backtracks],
/*skip_insignificant*/ true);
return ast ? ast->formatForLogging(settings[Setting::log_queries_cut_to_length]) : "";
}
QueryLogElement logQueryStart(
const std::chrono::time_point<std::chrono::system_clock> & query_start_time,
const ContextMutablePtr & context,
const String & query_for_logging,
UInt64 normalized_query_hash,
const ASTPtr & query_ast,
const QueryPipeline & pipeline,
const IInterpreter * interpreter,
bool internal,
bool log_as_internal,
const String & query_database,
const String & query_table,
bool async_insert)
{
const Settings & settings = context->getSettingsRef();
QueryLogElement elem;
elem.type = QueryLogElementType::QUERY_START;
elem.event_time = timeInSeconds(query_start_time);
elem.event_time_microseconds = timeInMicroseconds(query_start_time);
elem.query_start_time = timeInSeconds(query_start_time);
elem.query_start_time_microseconds = timeInMicroseconds(query_start_time);
elem.current_database = context->getCurrentDatabase();
elem.query = query_for_logging;
if (query_ast && settings[Setting::log_formatted_queries])
elem.formatted_query = query_ast->formatForLogging();
elem.normalized_query_hash = normalized_query_hash;
elem.query_kind = query_ast ? query_ast->getQueryKind() : IAST::QueryKind::Select;
elem.client_info = context->getClientInfo();
elem.http_handler_name = context->getHTTPHandlerName();
elem.http_request_url = httpRequestURLForLogging(context);
elem.is_internal = log_as_internal;
if (auto txn = context->getCurrentTransaction())
elem.tid = txn->tid;
bool log_queries = settings[Setting::log_queries];
auto query_log = context->getQueryLog();
if (!query_log)
return elem;
/// Log into system table start of query execution, if need.
if (log_queries)
{
/// This check is not obvious, but without it 01220_scalar_optimization_in_alter fails.
if (pipeline.initialized())
{
const auto & info = context->getQueryAccessInfo();
std::lock_guard lock(info.mutex);
elem.query_databases = info.databases;
elem.query_tables = info.tables;
elem.query_columns = info.columns;
elem.query_partitions = info.partitions;
elem.query_projections = info.projections;
elem.used_data_skipping_indices = info.data_skipping_indices;
elem.query_views = info.views;
elem.used_row_policies = info.row_policies;
}
if (async_insert)
InterpreterInsertQuery::extendQueryLogElemImpl(elem, context);
else if (interpreter)
interpreter->extendQueryLogElem(elem, query_ast, context, query_database, query_table);
elem.log_comment = settings[Setting::log_comment];
/// `max_query_size = 0` means "unlimited" everywhere else, so it must not truncate the comment to nothing.
if (settings[Setting::max_query_size] != 0 && elem.log_comment.size() > settings[Setting::max_query_size])
elem.log_comment.resize(settings[Setting::max_query_size]);
if (elem.type >= settings[Setting::log_queries_min_type] && !settings[Setting::log_queries_min_query_duration_ms].totalMilliseconds())
{
if (settings[Setting::log_query_settings])
elem.query_settings = settings.changedToFlatMap(/* show_secrets */ false);
else if (settings[Setting::log_query_settings].changed)
LOG_TRACE(
getLogger("executeQuery"),
"Not adding query settings to 'system.query_log' since setting `log_query_settings` is false"
" (the setting was changed for the query).");
query_log->add([&](QueryLogElement & e) { e = elem; });
}
else if (elem.type < settings[Setting::log_queries_min_type])
{
if (settings[Setting::log_queries_min_type].changed)
LOG_TRACE(
getLogger("executeQuery"),
"Not adding query start record to 'system.query_log' because the query type is smaller than setting `log_queries_min_type`"
" (the setting was changed for the query).");
}
else if (settings[Setting::log_queries_min_query_duration_ms].totalMilliseconds())
{
if (settings[Setting::log_queries_min_query_duration_ms].changed)
LOG_TRACE(
getLogger("executeQuery"),
"Not adding query start record to 'system.query_log' since setting `log_queries_min_query_duration_ms` > 0"
" (the setting was changed for the query).");
}
}
else if (!internal && !settings[Setting::log_queries])
{
if (settings[Setting::log_queries].changed)
LOG_TRACE(
getLogger("executeQuery"),
"Not adding query to 'system.query_log' since setting `log_queries` is false"
" (the setting was changed for the query).");
}
if (auto query_metric_log = context->getQueryMetricLog(); query_metric_log && !internal)
{
auto interval_milliseconds = getQueryMetricLogInterval(context);
if (interval_milliseconds > 0)
query_metric_log->startQuery(elem.client_info.current_query_id, query_start_time, interval_milliseconds);
}
return elem;
}
static void logQueryMetricLogFinish(ContextPtr context, bool internal, String query_id, std::chrono::system_clock::time_point finish_time, QueryStatusInfoPtr info)
{
if (auto query_metric_log = context->getQueryMetricLog(); query_metric_log && !internal)
{
auto interval_milliseconds = getQueryMetricLogInterval(context);
if (info && interval_milliseconds > 0)
{
/// Only collect data on query finish if the elapsed time exceeds the interval to collect.
/// If we don't do this, it's counter-intuitive to have a single entry for every quick query
/// where the data is basically a subset of the query_log.
/// On the other hand, it's very convenient to have a new entry whenever the query finishes
/// so that we can get nice time-series querying only query_metric_log without the need
/// to query the final state in query_log.
auto collect_on_finish = info->elapsed_microseconds > interval_milliseconds * 1000;
auto query_info = collect_on_finish ? info : nullptr;
query_metric_log->finishQuery(query_id, finish_time, query_info);
}
else
{
query_metric_log->finishQuery(query_id, finish_time, nullptr);
}
}
}
static ResultProgress flushQueryProgress(const QueryPipeline & pipeline, bool pulling_pipeline, const ProgressCallback & progress_callback, QueryStatusPtr process_list_elem)
{
ResultProgress res(0, 0, 0);
if (pulling_pipeline)
{
pipeline.tryGetResultRowsAndBytes(res.result_rows, res.result_bytes);
}
else if (process_list_elem) /// will be used only for ordinary INSERT queries
{
auto progress_out = process_list_elem->getProgressOut();
res.result_rows = progress_out.written_rows;
res.result_bytes = progress_out.written_bytes;
}
/// Report same memory_usage in X-ClickHouse-Summary as in query_log
if (process_list_elem)
res.memory_usage = std::max<Int64>(process_list_elem->getInfo().peak_memory_usage, 0);
if (progress_callback)
{
Progress p;
p.incrementPiecewiseAtomically(Progress{res});
progress_callback(p);
}
return res;
}
static QueryPipelineFinalizedInfo finalizeQueryPipelineBeforeLogging(QueryPipeline && query_pipeline, QueryResultCacheUsage /*query_result_cache_usage*/, bool pulling_pipeline, const ContextPtr & context)
{
/// Trigger the actual write of the buffered query result into the query result cache. This is done explicitly to
/// prevent partial/garbage results in case of exceptions during query execution.
/// Always called (it's a no-op if no cache writers exist in the pipeline), because subqueries may have
/// opted in to caching via explicit SETTINGS use_query_cache = true even when the outer query doesn't use the cache.
query_pipeline.finalizeWriteInQueryResultCache();
VectorWithMemoryTracking<ProcessorsProfileLogInfo> processors_profile_infos = getProcessorsProfileLogInfo(query_pipeline.getProcessors());
String pipeline_dump;
{
WriteBufferFromString out(pipeline_dump);
printPipeline(query_pipeline.getProcessors(), out, true);
}
std::optional<ResultProgress> result_progress;
if (pulling_pipeline)
{
UInt64 result_rows = 0;
UInt64 result_bytes = 0;
query_pipeline.tryGetResultRowsAndBytes(result_rows, result_bytes);
result_progress = std::make_optional<ResultProgress>(result_rows, result_bytes, 0);
}
if (auto plan_log_capture = context->getPlanLogCapture())
plan_log_capture->captureStatistics(query_pipeline);
/// Reset pipeline before fetching profile counters
query_pipeline.reset();
/// Update performance counters before logging to query_log
CurrentThread::finalizePerformanceCounters();
return QueryPipelineFinalizedInfo{
.result_progress = std::move(result_progress),
.processors_profile_infos = std::move(processors_profile_infos),
.pipeline_dump = std::move(pipeline_dump)};
}
static bool isAsyncInsertFlush(const ASTPtr & query_ast)
{
return query_ast && query_ast->getQueryKind() == IAST::QueryKind::AsyncInsertFlush;
}
/// Accounts the profile events accumulated by a finished (or failed) query against the quotas
/// defining limits over profile events. Called once per query at its end, after the performance
/// counters of its threads have been finalized and, for a failed query, after the `FailedQuery`
/// family of events has been incremented, so that the snapshot contains everything the query
/// produced. When no governing quota defines such limits, the cost is one atomic load: no
/// snapshot of the counters is taken.
///
/// A query cancelled without an exception does not go through `addStatusInfoToQueryLogElement`, so the
/// time-based events (`QueryTimeMicroseconds` and friends) have not been incremented for it. For such a
/// query, `cancelled_query_ast` is set, and they are added to what it is charged with here.
static void usedQuotaProfileEvents(
const std::shared_ptr<const EnabledQuota> & quota,
const QueryStatusPtr & process_list_elem,
UInt64 normalized_query_hash,
std::optional<ASTPtr> cancelled_query_ast = {})
{
if (!quota || !quota->hasProfileEventLimits() || !process_list_elem)
return;
auto info = process_list_elem->getInfo(false, /* get_profile_events= */ true);
auto counters = info.profile_counters;
auto excluded = process_list_elem->getExcludedProfileEvents();
if (counters && (excluded || cancelled_query_ast))
{
ProfileEvents::Counters own_counters(VariableContext::Process, /* parent = */ nullptr);
for (auto event = ProfileEvents::Event(0); event < ProfileEvents::end(); ++event)
{
/// What the nested queries charged on their own added to the local counters (see `excludeFromOuterQueryQuota`).
ProfileEvents::Count excluded_count = excluded ? (*excluded)[event] : 0;
if ((*counters)[event] > excluded_count)
own_counters.incrementNoTrace(event, (*counters)[event] - excluded_count);
}
if (cancelled_query_ast)
{
own_counters.incrementNoTrace(ProfileEvents::QueryTimeMicroseconds, info.elapsed_microseconds);
own_counters.incrementNoTrace(queryKindTimeEvent(*cancelled_query_ast), info.elapsed_microseconds);
}
counters = std::make_shared<ProfileEvents::Counters::Snapshot>(own_counters.getPartiallyAtomicSnapshot());
}
/// What the remote servers did for a distributed query, as they reported it (see `RemoteQueryExecutor`).
auto remote_counters = process_list_elem->getRemoteProfileEvents();
/// Both are charged in one call, so they land in the same quota interval.
/// `check_exceeded == false`: the query has already done its work, so it is allowed to
/// finish; the quota, now exhausted, rejects the following queries.
quota->usedProfileEvents(
normalized_query_hash,
{counters.get(), remote_counters ? &*remote_counters : nullptr},
/* check_exceeded = */ false);
}
/// Whether a query exempt from quotas (see `IInterpreter::ignoreQuota`) is charged against the quotas over profile events all the
/// same, because a scalar subquery not exempt from quotas has been executed while it was analyzed, in its thread group (see
/// `QueryStatus::executed_non_exempt_scalar_subquery`). The predefined counters of such a subquery are charged by its own pipeline.
static bool chargesExemptQueryProfileEvents(const QueryStatusPtr & process_list_elem)
{
return process_list_elem && process_list_elem->hasExecutedNonExemptScalarSubquery();
}
/// Whether the query is charged against the quotas over profile events. Like the predefined `errors`
/// counter, only the outer query of an internal one is, with one exception: the deferred flush of
/// asynchronous inserts, which is internal but runs on behalf of the user who submitted the inserts
/// and under their quota (it charges the predefined `written_bytes` as well).
static bool chargesQuotaProfileEvents(const ASTPtr & query_ast, bool internal)
{
return !internal || isAsyncInsertFlush(query_ast);
}
/// The normalized query hash the quotas of a query are charged by. For the deferred flush of asynchronous inserts,
/// it is the hash of the submitted inserts the quotas keyed by `normalized_query_hash` were checked against, which
/// `AsynchronousInsertQueue` sets in the context, rather than the hash of the flush's own statement.
static UInt64 quotaNormalizedQueryHash(const ASTPtr & query_ast, const ContextPtr & context, UInt64 normalized_query_hash)
{
return isAsyncInsertFlush(query_ast) ? context->getNormalizedQueryHash() : normalized_query_hash;
}
/// A flush of asynchronous inserts run by a query (`SYSTEM FLUSH ASYNC INSERT QUEUE t`) has its thread group nested in
/// the group of that query, so its counters add up to the counters of the query as well. Having been charged to the
/// user who submitted the inserts, they are excluded from what the outer query is charged with. Returns the outer
/// query to exclude them from.
static QueryStatusPtr getOuterQueryToExcludeFrom(const ASTPtr & query_ast)
{
if (!isAsyncInsertFlush(query_ast))
return nullptr;
auto group = CurrentThread::getGroup();
auto outer_group = group ? group->getParent() : nullptr;
if (!outer_group)
return nullptr;
auto outer_context = outer_group->query_context.lock();
if (!outer_context)
return nullptr;
/// Recorded even if the quota of the outer query has no limits over profile events at the moment: one can be added
/// by `ALTER QUOTA` before the outer query finishes, and the end-of-query accounting decides what is charged.
return outer_context->getProcessListElementSafe();
}
static void excludeFromOuterQueryQuota(const ASTPtr & query_ast, const QueryStatusPtr & process_list_elem)
{
if (!process_list_elem)
return;
if (auto outer_query = getOuterQueryToExcludeFrom(query_ast))
{
auto counters = process_list_elem->getInfo(false, /* get_profile_events= */ true).profile_counters;
if (counters)
outer_query->addExcludedProfileEvents(*counters);
}
}
/// The document is written into a buffer that grows from here up to the limit, rather than
/// starting at `DBMS_DEFAULT_BUFFER_SIZE`, which every plan would then allocate in full.
static constexpr size_t PLAN_RENDER_INITIAL_CHUNK_SIZE = 4096;
/// A row whose plan could not be written says why, in place of the plan.
static void writeQueryPlanError(String & query_plan, String reason)
{
/// The reason can be the message of any exception thrown while rendering the plan, which may
/// quote what it was rendering.
if (auto masker = SensitiveDataMasker::getInstance())
masker->wipeSensitiveData(reason);
query_plan.clear();
try
{
WriteBufferFromString out(query_plan);
FlatJSONPlanRenderer::renderError(reason, out);
out.finalize();
}
catch (...)
{
/// Ok to swallow: writing the error itself failed. An empty column takes its default of an
/// empty JSON object; a half-written document would not be valid JSON.
query_plan.clear();
}
}
static void attachQueryPlan(const ContextPtr & context, QueryLogElement & elem)
{
auto plan_log_capture = context->getPlanLogCapture();
if (!plan_log_capture)
return;
const auto & captured = plan_log_capture->getCapturedPlan();
if (!captured)
return;
/// Runs on the logging path of a query that has already returned its result, so failing to
/// write the plan must not fail the query. Producing the document is also the one part of
/// profiling that allocates in proportion to the plan, hence the blocker.
MemoryTrackerBlockerInThread block_memory_tracker;
const size_t max_size = context->getSettingsRef()[Setting::log_query_plans_max_size];
try
{
/// A query decides how much text its own plan contains, so the document is written into a
/// buffer that cannot grow past the limit rather than measured once it already has.
/// `MemoryWriteBuffer` throws rather than allocate the chunk that would cross it.
MemoryWriteBuffer plan_buffer(max_size, PLAN_RENDER_INITIAL_CHUNK_SIZE);
FlatJSONPlanRenderer renderer;
renderer.render(*captured, plan_buffer);
plan_buffer.finalize();
WriteBufferFromString out(elem.query_plan);
copyData(*plan_buffer.tryGetReadBuffer(), out);
out.finalize();
}
catch (const WriteBuffer::CurrentBufferExhausted &)
{
/// Not logged: a plan over the limit is a query's own doing, not a fault of the server,
/// and the row carries the reason. The exception says only that a buffer ran out, naming
/// neither the plan nor the setting, so the message is written here instead.
writeQueryPlanError(
elem.query_plan,
fmt::format("The query plan does not fit in {} bytes, the limit set by log_query_plans_max_size", max_size));
}
catch (...)
{
tryLogCurrentException(__PRETTY_FUNCTION__);
writeQueryPlanError(elem.query_plan, getCurrentExceptionMessage(/*with_stacktrace=*/ false));
}
}
/// Writes the bodies registered by `Context::addSQLSecurityOverriddenBody` as child rows of `elem`, without metrics.
static void logSQLSecurityOverriddenBodies(
QueryLog & query_log, const QueryLogElement & elem, Context::QueryAccessInfo & access_info, UInt64 max_query_length)
{
std::vector<std::shared_ptr<const Context::SQLSecurityOverriddenBody>> bodies;
{
std::lock_guard lock(access_info.mutex);
bodies.swap(access_info.sql_security_overridden_bodies);
}