executeQuery.cpp 37.5 KB
Newer Older
1
#include <Common/formatReadable.h>
2
#include <Common/PODArray.h>
3
#include <Common/typeid_cast.h>
4
#include <Common/ThreadProfileEvents.h>
5 6 7

#include <IO/ConcatReadBuffer.h>
#include <IO/WriteBufferFromFile.h>
8 9 10
#include <IO/WriteBufferFromVector.h>
#include <IO/LimitReadBuffer.h>
#include <IO/copyData.h>
11 12 13

#include <DataStreams/BlockIO.h>
#include <DataStreams/copyData.h>
14
#include <DataStreams/IBlockInputStream.h>
15 16 17 18
#include <DataStreams/InputStreamFromASTInsertQuery.h>
#include <DataStreams/CountingBlockOutputStream.h>

#include <Parsers/ASTInsertQuery.h>
19
#include <Parsers/ASTSelectQuery.h>
20 21 22 23 24
#include <Parsers/ASTShowProcesslistQuery.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTLiteral.h>
#include <Parsers/ParserQuery.h>
#include <Parsers/parseQuery.h>
25
#include <Parsers/queryToString.h>
26 27
#include <Parsers/ASTWatchQuery.h>
#include <Parsers/Lexer.h>
28

P
palasonicq 已提交
29 30
#include <Storages/StorageInput.h>

31
#include <Access/EnabledQuota.h>
32 33
#include <Interpreters/InterpreterFactory.h>
#include <Interpreters/ProcessList.h>
A
cleanup  
Alexander Kuzmenkov 已提交
34
#include <Interpreters/OpenTelemetrySpanLog.h>
35
#include <Interpreters/QueryLog.h>
36
#include <Interpreters/InterpreterSetQuery.h>
A
Amos Bird 已提交
37
#include <Interpreters/ApplyWithGlobalVisitor.h>
A
new  
Alexander Tretiakov 已提交
38
#include <Interpreters/ReplaceQueryParameterVisitor.h>
39
#include <Interpreters/executeQuery.h>
40
#include <Interpreters/Context.h>
M
Mikhail Filimonov 已提交
41
#include <Common/ProfileEvents.h>
42

43
#include <Interpreters/DNSCacheUpdater.h>
44
#include <Common/SensitiveDataMasker.h>
A
Alexey Milovidov 已提交
45

N
Nikolai Kochetov 已提交
46
#include <Processors/Transforms/LimitsCheckingTransform.h>
47
#include <Processors/Transforms/MaterializingTransform.h>
N
Nikolai Kochetov 已提交
48
#include <Processors/Formats/IOutputFormat.h>
A
Alexey Milovidov 已提交
49

A
Alexey Milovidov 已提交
50

M
Mikhail Filimonov 已提交
51 52 53
namespace ProfileEvents
{
    extern const Event QueryMaskingRulesMatch;
54 55 56
    extern const Event FailedQuery;
    extern const Event FailedInsertQuery;
    extern const Event FailedSelectQuery;
57 58 59
    extern const Event QueryTimeMicroseconds;
    extern const Event SelectQueryTimeMicroseconds;
    extern const Event InsertQueryTimeMicroseconds;
M
Mikhail Filimonov 已提交
60 61
}

A
Alexey Milovidov 已提交
62 63 64
namespace DB
{

65 66
namespace ErrorCodes
{
67
    extern const int INTO_OUTFILE_NOT_ALLOWED;
68
    extern const int QUERY_WAS_CANCELLED;
69 70
}

A
Alexey Milovidov 已提交
71

72
static void checkASTSizeLimits(const IAST & ast, const Settings & settings)
73
{
74 75 76 77
    if (settings.max_ast_depth)
        ast.checkDepth(settings.max_ast_depth);
    if (settings.max_ast_elements)
        ast.checkSize(settings.max_ast_elements);
78
}
79

80

81 82
static String joinLines(const String & query)
{
83
    /// Care should be taken. We don't join lines inside non-whitespace tokens (e.g. multiline string literals)
A
Alexey Milovidov 已提交
84
    ///  and we don't join line after comment (because it can be single-line comment).
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    /// All other whitespaces replaced to a single whitespace.

    String res;
    const char * begin = query.data();
    const char * end = begin + query.size();

    Lexer lexer(begin, end);
    Token token = lexer.nextToken();
    for (; !token.isEnd(); token = lexer.nextToken())
    {
        if (token.type == TokenType::Whitespace)
        {
            res += ' ';
        }
        else if (token.type == TokenType::Comment)
        {
            res.append(token.begin, token.end);
            if (token.end < end && *token.end == '\n')
                res += '\n';
        }
        else
            res.append(token.begin, token.end);
    }

109
    return res;
110 111 112
}


M
Mikhail Filimonov 已提交
113 114 115 116
static String prepareQueryForLogging(const String & query, Context & context)
{
    String res = query;

117 118
    // wiping sensitive data before cropping query by log_queries_cut_to_length,
    // otherwise something like credit card without last digit can go to log
A
Alexey Milovidov 已提交
119
    if (auto * masker = SensitiveDataMasker::getInstance())
M
Mikhail Filimonov 已提交
120 121 122 123 124 125 126
    {
        auto matches = masker->wipeSensitiveData(res);
        if (matches > 0)
        {
            ProfileEvents::increment(ProfileEvents::QueryMaskingRulesMatch, matches);
        }
    }
127 128 129

    res = res.substr(0, context.getSettingsRef().log_queries_cut_to_length);

M
Mikhail Filimonov 已提交
130 131 132 133
    return res;
}


134
/// Log query into text log (not into system table).
A
Alexey Milovidov 已提交
135
static void logQuery(const String & query, const Context & context, bool internal)
136
{
A
Alexey Milovidov 已提交
137 138
    if (internal)
    {
A
Alexey Milovidov 已提交
139
        LOG_DEBUG(&Poco::Logger::get("executeQuery"), "(internal) {}", joinLines(query));
A
Alexey Milovidov 已提交
140 141 142
    }
    else
    {
A
Alexander Kuzmenkov 已提交
143 144 145 146 147
        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;
A
Alexey Milovidov 已提交
148

A
Alexey Milovidov 已提交
149
        LOG_DEBUG(&Poco::Logger::get("executeQuery"), "(from {}{}{}) {}",
A
Alexander Kuzmenkov 已提交
150 151
            client_info.current_address.toString(),
            (current_user != "default" ? ", user: " + current_user : ""),
A
Alexey Milovidov 已提交
152 153
            (!initial_query_id.empty() && current_query_id != initial_query_id ? ", initial_query_id: " + initial_query_id : std::string()),
            joinLines(query));
A
Alexander Kuzmenkov 已提交
154

A
Alexander Kuzmenkov 已提交
155 156 157 158 159 160 161 162
        if (client_info.opentelemetry_trace_id)
        {
            LOG_TRACE(&Poco::Logger::get("executeQuery"),
                "OpenTelemetry trace id {:x}, span id {}, parent span id {}",
                client_info.opentelemetry_trace_id,
                client_info.opentelemetry_span_id,
                client_info.opentelemetry_parent_span_id);
        }
A
Alexey Milovidov 已提交
163
    }
164 165 166 167 168 169
}


/// Call this inside catch block.
static void setExceptionStackTrace(QueryLogElement & elem)
{
170 171
    /// Disable memory tracker for stack trace.
    /// Because if exception is "Memory limit (for query) exceed", then we probably can't allocate another one string.
172
    MemoryTracker::BlockerInThread temporarily_disable_memory_tracker;
173

174 175 176 177
    try
    {
        throw;
    }
178
    catch (const std::exception & e)
179
    {
180
        elem.stack_trace = getExceptionStackTraceString(e);
181 182
    }
    catch (...) {}
183 184 185 186 187 188
}


/// Log exception (with query info) into text log (not into system table).
static void logException(Context & context, QueryLogElement & elem)
{
A
Alexey Milovidov 已提交
189
    if (elem.stack_trace.empty())
A
Alexey Milovidov 已提交
190
        LOG_ERROR(&Poco::Logger::get("executeQuery"), "{} (from {}) (in query: {})",
A
Alexey Milovidov 已提交
191 192
            elem.exception, context.getClientInfo().current_address.toString(), joinLines(elem.query));
    else
A
Alexey Milovidov 已提交
193
        LOG_ERROR(&Poco::Logger::get("executeQuery"), "{} (from {}) (in query: {})"
A
Alexey Milovidov 已提交
194 195
            ", Stack trace (when copying this message, always include the lines below):\n\n{}",
            elem.exception, context.getClientInfo().current_address.toString(), joinLines(elem.query), elem.stack_trace);
196 197
}

198 199 200 201 202 203 204 205 206 207
inline UInt64 time_in_microseconds(std::chrono::time_point<std::chrono::system_clock> timepoint)
{
    return std::chrono::duration_cast<std::chrono::microseconds>(timepoint.time_since_epoch()).count();
}


inline UInt64 time_in_seconds(std::chrono::time_point<std::chrono::system_clock> timepoint)
{
    return std::chrono::duration_cast<std::chrono::seconds>(timepoint.time_since_epoch()).count();
}
208

209
static void onExceptionBeforeStart(const String & query_for_logging, Context & context, UInt64 current_time_us, ASTPtr ast)
210
{
211
    /// Exception before the query execution.
212 213
    if (auto quota = context.getQuota())
        quota->used(Quota::ERRORS, 1, /* check_exceeded = */ false);
214

215
    const Settings & settings = context.getSettingsRef();
216

217
    /// Log the start of query execution into the table if necessary.
218
    QueryLogElement elem;
219

220
    elem.type = QueryLogElementType::EXCEPTION_BEFORE_START;
221

222 223
    // all callers to onExceptionBeforeStart method construct the timespec for event_time and
    // event_time_microseconds from the same time point. So, it can be assumed that both of these
224
    // times are equal up to the precision of a second.
225
    elem.event_time = current_time_us / 1000000;
226
    elem.event_time_microseconds = current_time_us;
227 228
    elem.query_start_time = current_time_us / 1000000;
    elem.query_start_time_microseconds = current_time_us;
229

230
    elem.current_database = context.getCurrentDatabase();
M
Mikhail Filimonov 已提交
231
    elem.query = query_for_logging;
M
millb 已提交
232
    elem.exception_code = getCurrentExceptionCode();
233
    elem.exception = getCurrentExceptionMessage(false);
234

235
    elem.client_info = context.getClientInfo();
236

237 238
    if (settings.calculate_text_stack_trace)
        setExceptionStackTrace(elem);
239
    logException(context, elem);
240

241 242 243
    /// Update performance counters before logging to query_log
    CurrentThread::finalizePerformanceCounters();

244
    if (settings.log_queries && elem.type >= settings.log_queries_min_type)
245 246
        if (auto query_log = context.getQueryLog())
            query_log->add(elem);
247

A
cleanup  
Alexander Kuzmenkov 已提交
248
    if (auto opentelemetry_span_log = context.getOpenTelemetrySpanLog();
A
Alexander Kuzmenkov 已提交
249
        context.getClientInfo().opentelemetry_trace_id
A
cleanup  
Alexander Kuzmenkov 已提交
250
            && opentelemetry_span_log)
A
fixup  
Alexander Kuzmenkov 已提交
251 252
    {
        OpenTelemetrySpanLogElement span;
253 254 255
        span.trace_id = context.getClientInfo().opentelemetry_trace_id;
        span.span_id = context.getClientInfo().opentelemetry_span_id;
        span.parent_span_id = context.getClientInfo().opentelemetry_parent_span_id;
A
fixup  
Alexander Kuzmenkov 已提交
256
        span.operation_name = "query";
257 258
        span.start_time_us = current_time_us;
        span.finish_time_us = current_time_us;
A
Alexander Kuzmenkov 已提交
259
        span.duration_ns = 0;
A
fixup  
Alexander Kuzmenkov 已提交
260 261

        // keep values synchonized to type enum in QueryLogElement::createBlock
A
Alexander Kuzmenkov 已提交
262
        span.attribute_names.push_back("clickhouse.query_status");
A
fixup  
Alexander Kuzmenkov 已提交
263 264
        span.attribute_values.push_back("ExceptionBeforeStart");

A
Alexander Kuzmenkov 已提交
265
        span.attribute_names.push_back("db.statement");
A
fixup  
Alexander Kuzmenkov 已提交
266 267
        span.attribute_values.push_back(elem.query);

A
Alexander Kuzmenkov 已提交
268
        span.attribute_names.push_back("clickhouse.query_id");
A
fixup  
Alexander Kuzmenkov 已提交
269 270
        span.attribute_values.push_back(elem.client_info.current_query_id);

271 272
        if (!context.getClientInfo().opentelemetry_tracestate.empty())
        {
A
Alexander Kuzmenkov 已提交
273
            span.attribute_names.push_back("clickhouse.tracestate");
274 275 276 277
            span.attribute_values.push_back(
                context.getClientInfo().opentelemetry_tracestate);
        }

A
cleanup  
Alexander Kuzmenkov 已提交
278
        opentelemetry_span_log->add(span);
A
fixup  
Alexander Kuzmenkov 已提交
279 280
    }

281 282 283 284 285 286 287 288 289 290 291 292 293
    ProfileEvents::increment(ProfileEvents::FailedQuery);

    if (ast)
    {
        if (ast->as<ASTSelectQuery>() || ast->as<ASTSelectWithUnionQuery>())
        {
            ProfileEvents::increment(ProfileEvents::FailedSelectQuery);
        }
        else if (ast->as<ASTInsertQuery>())
        {
            ProfileEvents::increment(ProfileEvents::FailedInsertQuery);
        }
    }
294 295
}

296 297 298 299 300
static void setQuerySpecificSettings(ASTPtr & ast, Context & context)
{
    if (auto * ast_insert_into = dynamic_cast<ASTInsertQuery *>(ast.get()))
    {
        if (ast_insert_into->watch)
301
            context.setSetting("output_format_enable_streaming", 1);
302 303
    }
}
304

305
static std::tuple<ASTPtr, BlockIO> executeQueryImpl(
306 307
    const char * begin,
    const char * end,
308 309
    Context & context,
    bool internal,
A
alesapin 已提交
310
    QueryProcessingStage::Enum stage,
311
    bool has_query_tail,
312
    ReadBuffer * istr)
313
{
314
    const auto current_time = std::chrono::system_clock::now();
315

316 317 318 319 320 321 322
    /// If we already executing query and it requires to execute internal query, than
    /// don't replace thread context with given (it can be temporary). Otherwise, attach context to thread.
    if (!internal)
    {
        context.makeQueryContext();
        CurrentThread::attachQueryContext(context);
    }
323

324 325
    const Settings & settings = context.getSettingsRef();

I
Ivan 已提交
326
    ParserQuery parser(end);
327
    ASTPtr ast;
328
    const char * query_end;
329 330 331 332 333

    /// Don't limit the size of internal queries.
    size_t max_query_size = 0;
    if (!internal)
        max_query_size = settings.max_query_size;
334 335 336

    try
    {
337
        /// TODO Parser should fail early when max_query_size limit is reached.
338
        ast = parseQuery(parser, begin, end, "", max_query_size, settings.max_parser_depth);
339

I
Ivan Lezhankin 已提交
340
        auto * insert_query = ast->as<ASTInsertQuery>();
Z
zhang2014 已提交
341 342 343 344

        if (insert_query && insert_query->settings_ast)
            InterpreterSetQuery(insert_query->settings_ast, context).executeForCurrentContext();

345
        if (insert_query && insert_query->data)
A
alesapin 已提交
346
        {
347
            query_end = insert_query->data;
A
alesapin 已提交
348 349
            insert_query->has_tail = has_query_tail;
        }
350
        else
A
Alexey Milovidov 已提交
351
        {
352
            query_end = end;
A
Alexey Milovidov 已提交
353
        }
354 355 356
    }
    catch (...)
    {
A
Alexey Milovidov 已提交
357 358
        /// Anyway log the query.
        String query = String(begin, begin + std::min(end - begin, static_cast<ptrdiff_t>(max_query_size)));
M
Mikhail Filimonov 已提交
359 360 361

        auto query_for_logging = prepareQueryForLogging(query, context);
        logQuery(query_for_logging, context, internal);
A
Alexey Milovidov 已提交
362

363 364
        if (!internal)
        {
365
            onExceptionBeforeStart(query_for_logging, context, time_in_microseconds(current_time), ast);
366
        }
367

368 369
        throw;
    }
370

371 372
    setQuerySpecificSettings(ast, context);

373 374
    /// Copy query into string. It will be written to log and presented in processlist. If an INSERT query, string will not include data to insertion.
    String query(begin, query_end);
375
    BlockIO res;
376

A
Alexey Milovidov 已提交
377
    String query_for_logging;
M
Mikhail Filimonov 已提交
378

379 380
    try
    {
A
Alexey Milovidov 已提交
381
        /// Replace ASTQueryParameter with ASTLiteral for prepared statements.
A
Merging  
Alexey Milovidov 已提交
382 383 384 385
        if (context.hasQueryParameters())
        {
            ReplaceQueryParameterVisitor visitor(context.getQueryParameters());
            visitor.visit(ast);
386
            query = serializeAST(*ast);
A
Amos Bird 已提交
387
        }
A
Alexey Milovidov 已提交
388

389 390 391 392 393 394
        /// MUST goes before any modification (except for prepared statements,
        /// since it substitute parameters and w/o them query does not contains
        /// parameters), to keep query as-is in query_log and server log.
        query_for_logging = prepareQueryForLogging(query, context);
        logQuery(query_for_logging, context, internal);

A
Amos Bird 已提交
395 396 397 398 399
        /// Propagate WITH statement to children ASTSelect.
        if (settings.enable_global_with_statement)
        {
            ApplyWithGlobalVisitor().visit(ast);
            query = serializeAST(*ast);
400
        }
401

402
        /// Check the limits.
403
        checkASTSizeLimits(*ast, settings);
404 405 406

        /// Put query to process list. But don't put SHOW PROCESSLIST query itself.
        ProcessList::EntryPtr process_list_entry;
I
Ivan Lezhankin 已提交
407
        if (!internal && !ast->as<ASTShowProcesslistQuery>())
408
        {
M
Mikhail Filimonov 已提交
409 410
            /// processlist also has query masked now, to avoid secrets leaks though SHOW PROCESSLIST by other users.
            process_list_entry = context.getProcessList().insert(query_for_logging, ast.get(), context);
411 412 413
            context.setProcessListElement(&process_list_entry->get());
        }

414 415 416
        /// Load external tables if they were provided
        context.initializeExternalTablesIfSet();

P
palasonicq 已提交
417
        auto * insert_query = ast->as<ASTInsertQuery>();
418
        if (insert_query && insert_query->select)
P
palasonicq 已提交
419
        {
420
            /// Prepare Input storage before executing interpreter if we already got a buffer with data.
P
palasonicq 已提交
421 422
            if (istr)
            {
423
                ASTPtr input_function;
P
palasonicq 已提交
424
                insert_query->tryFindInputFunction(input_function);
425 426 427 428
                if (input_function)
                {
                    StoragePtr storage = context.executeTableFunction(input_function);
                    auto & input_storage = dynamic_cast<StorageInput &>(*storage);
429 430 431
                    auto input_metadata_snapshot = input_storage.getInMemoryMetadataPtr();
                    BlockInputStreamPtr input_stream = std::make_shared<InputStreamFromASTInsertQuery>(
                        ast, istr, input_metadata_snapshot->getSampleBlock(), context, input_function);
432 433
                    input_storage.setInputStream(input_stream);
                }
P
palasonicq 已提交
434 435 436 437 438 439
            }
        }
        else
            /// reset Input callbacks if query is not INSERT SELECT
            context.resetInputCallbacks();

440
        auto interpreter = InterpreterFactory::get(ast, context, stage);
N
Nikolai Kochetov 已提交
441

442
        std::shared_ptr<const EnabledQuota> quota;
443 444 445
        if (!interpreter->ignoreQuota())
        {
            quota = context.getQuota();
446 447 448 449 450
            if (quota)
            {
                quota->used(Quota::QUERIES, 1);
                quota->checkExceeded(Quota::ERRORS);
            }
451 452
        }

N
Nikolai Kochetov 已提交
453
        StreamLocalLimits limits;
454 455
        if (!interpreter->ignoreLimits())
        {
456
            limits.mode = LimitsMode::LIMITS_CURRENT;
457 458 459
            limits.size_limits = SizeLimits(settings.max_result_rows, settings.max_result_bytes, settings.result_overflow_mode);
        }

N
Nikolai Kochetov 已提交
460 461 462
        res = interpreter->execute();
        QueryPipeline & pipeline = res.pipeline;
        bool use_processors = pipeline.initialized();
N
Nikolai Kochetov 已提交
463

464 465 466
        if (res.pipeline.initialized())
            use_processors = true;

A
Alexey Milovidov 已提交
467
        if (const auto * insert_interpreter = typeid_cast<const InterpreterInsertQuery *>(&*interpreter))
468 469
        {
            /// Save insertion table (not table function). TODO: support remote() table function.
470 471 472
            auto table_id = insert_interpreter->getDatabaseTable();
            if (!table_id.empty())
                context.setInsertionTable(std::move(table_id));
473
        }
474 475

        if (process_list_entry)
476 477 478 479 480
        {
            /// Query was killed before execution
            if ((*process_list_entry)->isKilled())
                throw Exception("Query '" + (*process_list_entry)->getInfo().client_info.current_query_id + "' is killed in pending state",
                    ErrorCodes::QUERY_WAS_CANCELLED);
N
Nikolai Kochetov 已提交
481
            else if (!use_processors)
482 483
                (*process_list_entry)->setQueryStreams(res);
        }
484 485 486 487

        /// Hold element of process list till end of query execution.
        res.process_list_entry = process_list_entry;

N
Nikolai Kochetov 已提交
488
        if (use_processors)
489
        {
490 491
            /// Limits on the result, the quota on the result, and also callback for progress.
            /// Limits apply only to the final result.
492 493
            pipeline.setProgressCallback(context.getProgressCallback());
            pipeline.setProcessListElement(context.getProcessListElement());
494
            if (stage == QueryProcessingStage::Complete && !pipeline.isCompleted())
495
            {
N
Nikolai Kochetov 已提交
496
                pipeline.resize(1);
N
Nikolai Kochetov 已提交
497 498
                pipeline.addSimpleTransform([&](const Block & header)
                {
N
Nikolai Kochetov 已提交
499 500 501 502
                    auto transform = std::make_shared<LimitsCheckingTransform>(header, limits);
                    transform->setQuota(quota);
                    return transform;
                });
503 504
            }
        }
N
Nikolai Kochetov 已提交
505
        else
506
        {
507 508
            /// Limits on the result, the quota on the result, and also callback for progress.
            /// Limits apply only to the final result.
N
Nikolai Kochetov 已提交
509
            if (res.in)
510
            {
N
Nikolai Kochetov 已提交
511 512 513 514
                res.in->setProgressCallback(context.getProgressCallback());
                res.in->setProcessListElement(context.getProcessListElement());
                if (stage == QueryProcessingStage::Complete)
                {
515 516 517 518
                    if (!interpreter->ignoreQuota())
                        res.in->setQuota(quota);
                    if (!interpreter->ignoreLimits())
                        res.in->setLimits(limits);
N
Nikolai Kochetov 已提交
519 520 521 522
                }
            }

            if (res.out)
523
            {
A
Alexey Milovidov 已提交
524
                if (auto * stream = dynamic_cast<CountingBlockOutputStream *>(res.out.get()))
N
Nikolai Kochetov 已提交
525 526 527
                {
                    stream->setProcessListElement(context.getProcessListElement());
                }
528 529 530 531 532 533 534
            }
        }

        /// Everything related to query log.
        {
            QueryLogElement elem;

535
            elem.type = QueryLogElementType::QUERY_START;
536

537
            elem.event_time = time_in_seconds(current_time);
538
            elem.event_time_microseconds = time_in_microseconds(current_time);
539 540
            elem.query_start_time = time_in_seconds(current_time);
            elem.query_start_time_microseconds = time_in_microseconds(current_time);
541

542
            elem.current_database = context.getCurrentDatabase();
M
Mikhail Filimonov 已提交
543
            elem.query = query_for_logging;
544 545 546 547 548 549

            elem.client_info = context.getClientInfo();

            bool log_queries = settings.log_queries && !internal;

            /// Log into system table start of query execution, if need.
550
            if (log_queries)
551
            {
552 553 554
                if (settings.log_query_settings)
                    elem.query_settings = std::make_shared<Settings>(context.getSettingsRef());

555 556 557 558 559
                if (elem.type >= settings.log_queries_min_type)
                {
                    if (auto query_log = context.getQueryLog())
                        query_log->add(elem);
                }
560
            }
561

562
            /// Common code for finish and exception callbacks
563
            auto status_info_to_query_log = [](QueryLogElement &element, const QueryStatusInfo &info, const ASTPtr query_ast) mutable
564 565 566
            {
                DB::UInt64 query_time = info.elapsed_seconds * 1000000;
                ProfileEvents::increment(ProfileEvents::QueryTimeMicroseconds, query_time);
567
                if (query_ast->as<ASTSelectQuery>() || query_ast->as<ASTSelectWithUnionQuery>())
568 569 570
                {
                    ProfileEvents::increment(ProfileEvents::SelectQueryTimeMicroseconds, query_time);
                }
571
                else if (query_ast->as<ASTInsertQuery>())
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
                {
                    ProfileEvents::increment(ProfileEvents::InsertQueryTimeMicroseconds, query_time);
                }

                element.query_duration_ms = info.elapsed_seconds * 1000;

                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 = std::move(info.thread_ids);
                element.profile_counters = std::move(info.profile_counters);
            };

590
            /// Also make possible for caller to log successful query finish and exception during execution.
591 592
            auto finish_callback = [elem, &context, ast, log_queries, log_queries_min_type = settings.log_queries_min_type,
                status_info_to_query_log]
593
                (IBlockInputStream * stream_in, IBlockOutputStream * stream_out, QueryPipeline * query_pipeline) mutable
594
            {
595
                QueryStatus * process_list_elem = context.getProcessListElement();
596 597 598 599

                if (!process_list_elem)
                    return;

600
                /// Update performance counters before logging to query_log
601
                CurrentThread::finalizePerformanceCounters();
602

603
                QueryStatusInfo info = process_list_elem->getInfo(true, context.getSettingsRef().log_profile_events);
604 605

                double elapsed_seconds = info.elapsed_seconds;
606

607
                elem.type = QueryLogElementType::QUERY_FINISH;
608

609 610
                // construct event_time and event_time_microseconds using the same time point
                // so that the two times will always be equal up to a precision of a second.
A
Alexander Kuzmenkov 已提交
611 612
                const auto finish_time = std::chrono::system_clock::now();
                elem.event_time = time_in_seconds(finish_time);
613
                elem.event_time_microseconds = time_in_microseconds(finish_time);
614
                status_info_to_query_log(elem, info, ast);
615

616
                auto progress_callback = context.getProgressCallback();
G
Guillaume Tassery 已提交
617

618 619 620
                if (progress_callback)
                    progress_callback(Progress(WriteProgress(info.written_rows, info.written_bytes)));

621 622
                if (stream_in)
                {
623
                    const BlockStreamProfileInfo & stream_in_info = stream_in->getProfileInfo();
624

625 626 627
                    /// NOTE: INSERT SELECT query contains zero metrics
                    elem.result_rows = stream_in_info.rows;
                    elem.result_bytes = stream_in_info.bytes;
628 629 630
                }
                else if (stream_out) /// will be used only for ordinary INSERT queries
                {
A
Alexey Milovidov 已提交
631
                    if (const auto * counting_stream = dynamic_cast<const CountingBlockOutputStream *>(stream_out))
632
                    {
M
maiha 已提交
633
                        /// NOTE: Redundancy. The same values could be extracted from process_list_elem->progress_out.query_settings = process_list_elem->progress_in
634 635
                        elem.result_rows = counting_stream->getProgress().read_rows;
                        elem.result_bytes = counting_stream->getProgress().read_bytes;
636 637
                    }
                }
638 639 640 641 642 643 644 645
                else if (query_pipeline)
                {
                    if (const auto * output_format = query_pipeline->getOutputFormat())
                    {
                        elem.result_rows = output_format->getResultRows();
                        elem.result_bytes = output_format->getResultBytes();
                    }
                }
646 647 648

                if (elem.read_rows != 0)
                {
A
Alexey Milovidov 已提交
649
                    LOG_INFO(&Poco::Logger::get("executeQuery"), "Read {} rows, {} in {} sec., {} rows/sec., {}/sec.",
650
                        elem.read_rows, ReadableSize(elem.read_bytes), elapsed_seconds,
A
Alexey Milovidov 已提交
651
                        static_cast<size_t>(elem.read_rows / elapsed_seconds),
652
                        ReadableSize(elem.read_bytes / elapsed_seconds));
653 654
                }

A
Alexey Milovidov 已提交
655
                elem.thread_ids = std::move(info.thread_ids);
656 657
                elem.profile_counters = std::move(info.profile_counters);

658
                if (log_queries && elem.type >= log_queries_min_type)
659 660 661 662
                {
                    if (auto query_log = context.getQueryLog())
                        query_log->add(elem);
                }
A
Alexander Kuzmenkov 已提交
663

A
cleanup  
Alexander Kuzmenkov 已提交
664
                if (auto opentelemetry_span_log = context.getOpenTelemetrySpanLog();
A
Alexander Kuzmenkov 已提交
665
                    context.getClientInfo().opentelemetry_trace_id
A
cleanup  
Alexander Kuzmenkov 已提交
666
                        && opentelemetry_span_log)
A
Alexander Kuzmenkov 已提交
667
                {
A
fixup  
Alexander Kuzmenkov 已提交
668
                    OpenTelemetrySpanLogElement span;
669 670 671
                    span.trace_id = context.getClientInfo().opentelemetry_trace_id;
                    span.span_id = context.getClientInfo().opentelemetry_span_id;
                    span.parent_span_id = context.getClientInfo().opentelemetry_parent_span_id;
A
fixup  
Alexander Kuzmenkov 已提交
672
                    span.operation_name = "query";
673
                    span.start_time_us = elem.query_start_time_microseconds;
A
Alexander Kuzmenkov 已提交
674
                    span.finish_time_us = time_in_microseconds(finish_time);
A
Alexander Kuzmenkov 已提交
675
                    span.duration_ns = elapsed_seconds * 1000000000;
A
fixup  
Alexander Kuzmenkov 已提交
676 677

                    // keep values synchonized to type enum in QueryLogElement::createBlock
A
Alexander Kuzmenkov 已提交
678
                    span.attribute_names.push_back("clickhouse.query_status");
A
fixup  
Alexander Kuzmenkov 已提交
679 680
                    span.attribute_values.push_back("QueryFinish");

A
Alexander Kuzmenkov 已提交
681
                    span.attribute_names.push_back("db.statement");
A
fixup  
Alexander Kuzmenkov 已提交
682 683
                    span.attribute_values.push_back(elem.query);

A
Alexander Kuzmenkov 已提交
684
                    span.attribute_names.push_back("clickhouse.query_id");
A
fixup  
Alexander Kuzmenkov 已提交
685
                    span.attribute_values.push_back(elem.client_info.current_query_id);
686 687
                    if (!context.getClientInfo().opentelemetry_tracestate.empty())
                    {
A
Alexander Kuzmenkov 已提交
688
                        span.attribute_names.push_back("clickhouse.tracestate");
689 690 691
                        span.attribute_values.push_back(
                            context.getClientInfo().opentelemetry_tracestate);
                    }
A
fixup  
Alexander Kuzmenkov 已提交
692

A
cleanup  
Alexander Kuzmenkov 已提交
693
                    opentelemetry_span_log->add(span);
A
Alexander Kuzmenkov 已提交
694
                }
695 696
            };

697 698
            auto exception_callback = [elem, &context, ast, log_queries, log_queries_min_type = settings.log_queries_min_type, quota(quota),
                    status_info_to_query_log] () mutable
699
            {
700 701
                if (quota)
                    quota->used(Quota::ERRORS, 1, /* check_exceeded = */ false);
702

703
                elem.type = QueryLogElementType::EXCEPTION_WHILE_PROCESSING;
704

705
                // event_time and event_time_microseconds are being constructed from the same time point
706
                // to ensure that both the times will be equal up to the precision of a second.
707
                const auto time_now = std::chrono::system_clock::now();
708

709 710
                elem.event_time = time_in_seconds(time_now);
                elem.event_time_microseconds = time_in_microseconds(time_now);
711
                elem.query_duration_ms = 1000 * (elem.event_time - elem.query_start_time);
M
millb 已提交
712
                elem.exception_code = getCurrentExceptionCode();
713 714
                elem.exception = getCurrentExceptionMessage(false);

715
                QueryStatus * process_list_elem = context.getProcessListElement();
716
                const Settings & current_settings = context.getSettingsRef();
717

718
                /// Update performance counters before logging to query_log
719
                CurrentThread::finalizePerformanceCounters();
720

721 722
                if (process_list_elem)
                {
723
                    QueryStatusInfo info = process_list_elem->getInfo(true, current_settings.log_profile_events, false);
724
                    status_info_to_query_log(elem, info, ast);
725
                }
726

727
                if (current_settings.calculate_text_stack_trace)
728
                    setExceptionStackTrace(elem);
729
                logException(context, elem);
730

731
                /// In case of exception we log internal queries also
732
                if (log_queries && elem.type >= log_queries_min_type)
733 734 735 736
                {
                    if (auto query_log = context.getQueryLog())
                        query_log->add(elem);
                }
737 738

                ProfileEvents::increment(ProfileEvents::FailedQuery);
N
Nikita Orlov 已提交
739 740
                if (ast->as<ASTSelectQuery>() || ast->as<ASTSelectWithUnionQuery>())
                {
741 742
                    ProfileEvents::increment(ProfileEvents::FailedSelectQuery);
                }
N
Nikita Orlov 已提交
743 744 745 746
                else if (ast->as<ASTInsertQuery>())
                {
                    ProfileEvents::increment(ProfileEvents::FailedInsertQuery);
                }
747

748
            };
749

N
Nikolai Kochetov 已提交
750 751
            res.finish_callback = std::move(finish_callback);
            res.exception_callback = std::move(exception_callback);
N
Nikolai Kochetov 已提交
752

753 754 755 756 757
            if (!internal && res.in)
            {
                std::stringstream log_str;
                log_str << "Query pipeline:\n";
                res.in->dumpTree(log_str);
A
Alexey Milovidov 已提交
758
                LOG_DEBUG(&Poco::Logger::get("executeQuery"), log_str.str());
759 760 761 762 763 764
            }
        }
    }
    catch (...)
    {
        if (!internal)
M
Mikhail Filimonov 已提交
765 766 767 768
        {
            if (query_for_logging.empty())
                query_for_logging = prepareQueryForLogging(query, context);

769
            onExceptionBeforeStart(query_for_logging, context, time_in_microseconds(current_time), ast);
M
Mikhail Filimonov 已提交
770
        }
771 772 773 774

        throw;
    }

775
    return std::make_tuple(ast, std::move(res));
776 777 778 779
}


BlockIO executeQuery(
780 781 782
    const String & query,
    Context & context,
    bool internal,
783
    QueryProcessingStage::Enum stage,
784
    bool may_have_embedded_data)
785
{
A
Amos Bird 已提交
786
    ASTPtr ast;
787
    BlockIO streams;
A
Amos Bird 已提交
788
    std::tie(ast, streams) = executeQueryImpl(query.data(), query.data() + query.size(), context,
789
        internal, stage, !may_have_embedded_data, nullptr);
790 791

    if (const auto * ast_query_with_output = dynamic_cast<const ASTQueryWithOutput *>(ast.get()))
A
Amos Bird 已提交
792
    {
793 794 795 796
        String format_name = ast_query_with_output->format
                ? getIdentifierName(ast_query_with_output->format)
                : context.getDefaultFormat();

A
Amos Bird 已提交
797 798 799
        if (format_name == "Null")
            streams.null_format = true;
    }
800

801
    return streams;
802 803
}

N
Nikolai Kochetov 已提交
804 805 806 807 808 809 810 811
BlockIO executeQuery(
        const String & query,
        Context & context,
        bool internal,
        QueryProcessingStage::Enum stage,
        bool may_have_embedded_data,
        bool allow_processors)
{
N
Nikolai Kochetov 已提交
812
    BlockIO res = executeQuery(query, context, internal, stage, may_have_embedded_data);
N
Nikolai Kochetov 已提交
813 814 815 816 817 818 819

    if (!allow_processors && res.pipeline.initialized())
        res.in = res.getInputStream();

    return res;
}

820

A
Alexey Milovidov 已提交
821
void executeQuery(
822 823 824 825
    ReadBuffer & istr,
    WriteBuffer & ostr,
    bool allow_into_outfile,
    Context & context,
826
    std::function<void(const String &, const String &, const String &, const String &)> set_result_details)
A
Alexey Milovidov 已提交
827
{
828 829 830 831 832
    PODArray<char> parse_buf;
    const char * begin;
    const char * end;

    /// If 'istr' is empty now, fetch next data into buffer.
A
Alexander Kuzmenkov 已提交
833
    if (!istr.hasPendingData())
834 835 836 837
        istr.next();

    size_t max_query_size = context.getSettingsRef().max_query_size;

838
    bool may_have_tail;
N
Nikolai Kochetov 已提交
839
    if (istr.buffer().end() - istr.position() > static_cast<ssize_t>(max_query_size))
840 841 842 843 844
    {
        /// If remaining buffer space in 'istr' is enough to parse query up to 'max_query_size' bytes, then parse inplace.
        begin = istr.position();
        end = istr.buffer().end();
        istr.position() += end - begin;
845 846 847
        /// Actually we don't know will query has additional data or not.
        /// But we can't check istr.eof(), because begin and end pointers will became invalid
        may_have_tail = true;
848 849 850 851
    }
    else
    {
        /// If not - copy enough data into 'parse_buf'.
852 853 854
        WriteBufferFromVector<PODArray<char>> out(parse_buf);
        LimitReadBuffer limit(istr, max_query_size + 1, false);
        copyData(limit, out);
A
Alexander Burmak 已提交
855
        out.finalize();
856

857
        begin = parse_buf.data();
858
        end = begin + parse_buf.size();
859 860
        /// Can check stream for eof, because we have copied data
        may_have_tail = !istr.eof();
861 862 863 864 865
    }

    ASTPtr ast;
    BlockIO streams;

866
    std::tie(ast, streams) = executeQueryImpl(begin, end, context, false, QueryProcessingStage::Complete, may_have_tail, &istr);
867

N
Nikolai Kochetov 已提交
868 869
    auto & pipeline = streams.pipeline;

870 871 872 873
    try
    {
        if (streams.out)
        {
874
            InputStreamFromASTInsertQuery in(ast, &istr, streams.out->getHeader(), context, nullptr);
875 876
            copyData(in, *streams.out);
        }
A
Amos Bird 已提交
877
        else if (streams.in)
878
        {
879 880
            /// FIXME: try to prettify this cast using `as<>()`
            const auto * ast_query_with_output = dynamic_cast<const ASTQueryWithOutput *>(ast.get());
881 882

            WriteBuffer * out_buf = &ostr;
883
            std::optional<WriteBufferFromFile> out_file_buf;
884 885 886 887 888
            if (ast_query_with_output && ast_query_with_output->out_file)
            {
                if (!allow_into_outfile)
                    throw Exception("INTO OUTFILE is not allowed", ErrorCodes::INTO_OUTFILE_NOT_ALLOWED);

889
                const auto & out_file = ast_query_with_output->out_file->as<ASTLiteral &>().value.safeGet<std::string>();
890
                out_file_buf.emplace(out_file, DBMS_DEFAULT_BUFFER_SIZE, O_WRONLY | O_EXCL | O_CREAT);
891
                out_buf = &*out_file_buf;
892 893 894
            }

            String format_name = ast_query_with_output && (ast_query_with_output->format != nullptr)
A
Alexey Milovidov 已提交
895
                ? getIdentifierName(ast_query_with_output->format)
896 897
                : context.getDefaultFormat();

A
Alexey Milovidov 已提交
898 899
            if (ast_query_with_output && ast_query_with_output->settings_ast)
                InterpreterSetQuery(ast_query_with_output->settings_ast, context).executeForCurrentContext();
900

901
            BlockOutputStreamPtr out = context.getOutputFormat(format_name, *out_buf, streams.in->getHeader());
902

903 904
            /// Save previous progress callback if any. TODO Do it more conveniently.
            auto previous_progress_callback = context.getProgressCallback();
905

906 907 908 909 910 911 912
            /// NOTE Progress callback takes shared ownership of 'out'.
            streams.in->setProgressCallback([out, previous_progress_callback] (const Progress & progress)
            {
                if (previous_progress_callback)
                    previous_progress_callback(progress);
                out->onProgress(progress);
            });
913

914 915
            if (set_result_details)
                set_result_details(context.getClientInfo().current_query_id, out->getContentType(), format_name, DateLUT::instance().getTimeZone());
916

917
            copyData(*streams.in, *out, [](){ return false; }, [&out](const Block &) { out->flush(); });
918
        }
A
Amos Bird 已提交
919
        else if (pipeline.initialized())
N
Nikolai Kochetov 已提交
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
        {
            const ASTQueryWithOutput * ast_query_with_output = dynamic_cast<const ASTQueryWithOutput *>(ast.get());

            WriteBuffer * out_buf = &ostr;
            std::optional<WriteBufferFromFile> out_file_buf;
            if (ast_query_with_output && ast_query_with_output->out_file)
            {
                if (!allow_into_outfile)
                    throw Exception("INTO OUTFILE is not allowed", ErrorCodes::INTO_OUTFILE_NOT_ALLOWED);

                const auto & out_file = typeid_cast<const ASTLiteral &>(*ast_query_with_output->out_file).value.safeGet<std::string>();
                out_file_buf.emplace(out_file, DBMS_DEFAULT_BUFFER_SIZE, O_WRONLY | O_EXCL | O_CREAT);
                out_buf = &*out_file_buf;
            }

            String format_name = ast_query_with_output && (ast_query_with_output->format != nullptr)
A
Alexey Milovidov 已提交
936
                                 ? getIdentifierName(ast_query_with_output->format)
N
Nikolai Kochetov 已提交
937 938 939 940 941
                                 : context.getDefaultFormat();

            if (ast_query_with_output && ast_query_with_output->settings_ast)
                InterpreterSetQuery(ast_query_with_output->settings_ast, context).executeForCurrentContext();

942
            if (!pipeline.isCompleted())
N
Nikolai Kochetov 已提交
943
            {
944 945 946 947
                pipeline.addSimpleTransform([](const Block & header)
                {
                    return std::make_shared<MaterializingTransform>(header);
                });
N
Nikolai Kochetov 已提交
948

949 950
                auto out = context.getOutputFormatProcessor(format_name, *out_buf, pipeline.getHeader());
                out->setAutoFlush();
N
Nikolai Kochetov 已提交
951

952 953
                /// Save previous progress callback if any. TODO Do it more conveniently.
                auto previous_progress_callback = context.getProgressCallback();
N
Nikolai Kochetov 已提交
954

955 956 957 958 959 960 961
                /// NOTE Progress callback takes shared ownership of 'out'.
                pipeline.setProgressCallback([out, previous_progress_callback] (const Progress & progress)
                {
                    if (previous_progress_callback)
                        previous_progress_callback(progress);
                    out->onProgress(progress);
                });
N
Nikolai Kochetov 已提交
962

963 964
                if (set_result_details)
                    set_result_details(context.getClientInfo().current_query_id, out->getContentType(), format_name, DateLUT::instance().getTimeZone());
N
Nikolai Kochetov 已提交
965

966 967 968 969 970 971
                pipeline.setOutputFormat(std::move(out));
            }
            else
            {
                pipeline.setProgressCallback(context.getProgressCallback());
            }
972

973
            {
N
Nikolai Kochetov 已提交
974
                auto executor = pipeline.execute();
975
                executor->execute(pipeline.getNumThreads());
976
            }
N
Nikolai Kochetov 已提交
977
        }
978 979 980 981 982 983 984 985
    }
    catch (...)
    {
        streams.onException();
        throw;
    }

    streams.onFinish();
986
}
987

A
Alexey Milovidov 已提交
988
}