executeQuery.cpp 34.3 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 34
#include <Interpreters/InterpreterFactory.h>
#include <Interpreters/ProcessList.h>
#include <Interpreters/QueryLog.h>
35
#include <Interpreters/InterpreterSetQuery.h>
A
Amos Bird 已提交
36
#include <Interpreters/ApplyWithGlobalVisitor.h>
A
new  
Alexander Tretiakov 已提交
37
#include <Interpreters/ReplaceQueryParameterVisitor.h>
38
#include <Interpreters/executeQuery.h>
39
#include <Interpreters/Context.h>
M
Mikhail Filimonov 已提交
40
#include <Common/ProfileEvents.h>
41

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

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

A
Alexey Milovidov 已提交
49

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

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

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

A
Alexey Milovidov 已提交
70

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

79

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

108
    return res;
109 110 111
}


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

116 117
    // 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 已提交
118
    if (auto * masker = SensitiveDataMasker::getInstance())
M
Mikhail Filimonov 已提交
119 120 121 122 123 124 125
    {
        auto matches = masker->wipeSensitiveData(res);
        if (matches > 0)
        {
            ProfileEvents::increment(ProfileEvents::QueryMaskingRulesMatch, matches);
        }
    }
126 127 128

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

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


133
/// Log query into text log (not into system table).
A
Alexey Milovidov 已提交
134
static void logQuery(const String & query, const Context & context, bool internal)
135
{
A
Alexey Milovidov 已提交
136 137
    if (internal)
    {
A
Alexey Milovidov 已提交
138
        LOG_DEBUG(&Poco::Logger::get("executeQuery"), "(internal) {}", joinLines(query));
A
Alexey Milovidov 已提交
139 140 141 142 143 144 145
    }
    else
    {
        const auto & current_query_id = context.getClientInfo().current_query_id;
        const auto & initial_query_id = context.getClientInfo().initial_query_id;
        const auto & current_user = context.getClientInfo().current_user;

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


/// Call this inside catch block.
static void setExceptionStackTrace(QueryLogElement & elem)
{
158 159
    /// Disable memory tracker for stack trace.
    /// Because if exception is "Memory limit (for query) exceed", then we probably can't allocate another one string.
160
    auto temporarily_disable_memory_tracker = getCurrentMemoryTrackerActionLock();
161

162 163 164 165
    try
    {
        throw;
    }
166
    catch (const std::exception & e)
167
    {
168
        elem.stack_trace = getExceptionStackTraceString(e);
169 170
    }
    catch (...) {}
171 172 173 174 175 176
}


/// Log exception (with query info) into text log (not into system table).
static void logException(Context & context, QueryLogElement & elem)
{
A
Alexey Milovidov 已提交
177
    if (elem.stack_trace.empty())
A
Alexey Milovidov 已提交
178
        LOG_ERROR(&Poco::Logger::get("executeQuery"), "{} (from {}) (in query: {})",
A
Alexey Milovidov 已提交
179 180
            elem.exception, context.getClientInfo().current_address.toString(), joinLines(elem.query));
    else
A
Alexey Milovidov 已提交
181
        LOG_ERROR(&Poco::Logger::get("executeQuery"), "{} (from {}) (in query: {})"
A
Alexey Milovidov 已提交
182 183
            ", 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);
184 185
}

186 187 188 189 190 191 192 193 194 195
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();
}
196

197
static void onExceptionBeforeStart(const String & query_for_logging, Context & context, time_t current_time, UInt64 current_time_microseconds, ASTPtr ast)
198
{
199
    /// Exception before the query execution.
200 201
    if (auto quota = context.getQuota())
        quota->used(Quota::ERRORS, 1, /* check_exceeded = */ false);
202

203
    const Settings & settings = context.getSettingsRef();
204

205
    /// Log the start of query execution into the table if necessary.
206
    QueryLogElement elem;
207

208
    elem.type = QueryLogElementType::EXCEPTION_BEFORE_START;
209

210 211
    // 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
212
    // times are equal upto the precision of a second.
213
    elem.event_time = current_time;
214
    elem.event_time_microseconds = current_time_microseconds;
215
    elem.query_start_time = current_time;
216
    elem.query_start_time_microseconds = current_time_microseconds;
217

218
    elem.current_database = context.getCurrentDatabase();
M
Mikhail Filimonov 已提交
219
    elem.query = query_for_logging;
M
millb 已提交
220
    elem.exception_code = getCurrentExceptionCode();
221
    elem.exception = getCurrentExceptionMessage(false);
222

223
    elem.client_info = context.getClientInfo();
224

225 226
    if (settings.calculate_text_stack_trace)
        setExceptionStackTrace(elem);
227
    logException(context, elem);
228

229 230 231
    /// Update performance counters before logging to query_log
    CurrentThread::finalizePerformanceCounters();

232
    if (settings.log_queries && elem.type >= settings.log_queries_min_type)
233 234
        if (auto query_log = context.getQueryLog())
            query_log->add(elem);
235 236 237 238 239 240 241 242 243 244 245 246 247 248

    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);
        }
    }
249 250
}

251 252 253 254 255
static void setQuerySpecificSettings(ASTPtr & ast, Context & context)
{
    if (auto * ast_insert_into = dynamic_cast<ASTInsertQuery *>(ast.get()))
    {
        if (ast_insert_into->watch)
256
            context.setSetting("output_format_enable_streaming", 1);
257 258
    }
}
259

260
static std::tuple<ASTPtr, BlockIO> executeQueryImpl(
261 262
    const char * begin,
    const char * end,
263 264
    Context & context,
    bool internal,
A
alesapin 已提交
265
    QueryProcessingStage::Enum stage,
266
    bool has_query_tail,
267
    ReadBuffer * istr)
268
{
269
    // current_time and current_time_microseconds are both constructed from the same time point
270
    // to ensure that both the times are equal upto the precision of a second.
271
    const auto now = std::chrono::system_clock::now();
272

273 274
    auto current_time = time_in_seconds(now);
    auto current_time_microseconds = time_in_microseconds(now);
275

276 277 278 279 280 281 282
    /// 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);
    }
283

284 285
    const Settings & settings = context.getSettingsRef();

286
    ParserQuery parser(end, settings.enable_debug_queries);
287
    ASTPtr ast;
288
    const char * query_end;
289 290 291 292 293

    /// Don't limit the size of internal queries.
    size_t max_query_size = 0;
    if (!internal)
        max_query_size = settings.max_query_size;
294 295 296

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

I
Ivan Lezhankin 已提交
300
        auto * insert_query = ast->as<ASTInsertQuery>();
Z
zhang2014 已提交
301 302 303 304

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

305
        if (insert_query && insert_query->data)
A
alesapin 已提交
306
        {
307
            query_end = insert_query->data;
A
alesapin 已提交
308 309
            insert_query->has_tail = has_query_tail;
        }
310
        else
A
Alexey Milovidov 已提交
311
        {
312
            query_end = end;
A
Alexey Milovidov 已提交
313
        }
314 315 316
    }
    catch (...)
    {
A
Alexey Milovidov 已提交
317 318
        /// Anyway log the query.
        String query = String(begin, begin + std::min(end - begin, static_cast<ptrdiff_t>(max_query_size)));
M
Mikhail Filimonov 已提交
319 320 321

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

323 324
        if (!internal)
        {
325
            onExceptionBeforeStart(query_for_logging, context, current_time, current_time_microseconds, ast);
326
        }
327

328 329
        throw;
    }
330

331 332
    setQuerySpecificSettings(ast, context);

333 334
    /// 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);
335
    BlockIO res;
336

A
Alexey Milovidov 已提交
337
    String query_for_logging;
M
Mikhail Filimonov 已提交
338

339 340
    try
    {
A
Alexey Milovidov 已提交
341
        /// Replace ASTQueryParameter with ASTLiteral for prepared statements.
A
Merging  
Alexey Milovidov 已提交
342 343 344 345
        if (context.hasQueryParameters())
        {
            ReplaceQueryParameterVisitor visitor(context.getQueryParameters());
            visitor.visit(ast);
346
            query = serializeAST(*ast);
A
Amos Bird 已提交
347
        }
A
Alexey Milovidov 已提交
348

349 350 351 352 353 354
        /// 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 已提交
355 356 357 358 359
        /// Propagate WITH statement to children ASTSelect.
        if (settings.enable_global_with_statement)
        {
            ApplyWithGlobalVisitor().visit(ast);
            query = serializeAST(*ast);
360
        }
361

362
        /// Check the limits.
363
        checkASTSizeLimits(*ast, settings);
364 365 366

        /// Put query to process list. But don't put SHOW PROCESSLIST query itself.
        ProcessList::EntryPtr process_list_entry;
I
Ivan Lezhankin 已提交
367
        if (!internal && !ast->as<ASTShowProcesslistQuery>())
368
        {
M
Mikhail Filimonov 已提交
369 370
            /// 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);
371 372 373
            context.setProcessListElement(&process_list_entry->get());
        }

374 375 376
        /// Load external tables if they were provided
        context.initializeExternalTablesIfSet();

P
palasonicq 已提交
377
        auto * insert_query = ast->as<ASTInsertQuery>();
378
        if (insert_query && insert_query->select)
P
palasonicq 已提交
379
        {
380
            /// Prepare Input storage before executing interpreter if we already got a buffer with data.
P
palasonicq 已提交
381 382
            if (istr)
            {
383
                ASTPtr input_function;
P
palasonicq 已提交
384
                insert_query->tryFindInputFunction(input_function);
385 386 387 388
                if (input_function)
                {
                    StoragePtr storage = context.executeTableFunction(input_function);
                    auto & input_storage = dynamic_cast<StorageInput &>(*storage);
389 390 391
                    auto input_metadata_snapshot = input_storage.getInMemoryMetadataPtr();
                    BlockInputStreamPtr input_stream = std::make_shared<InputStreamFromASTInsertQuery>(
                        ast, istr, input_metadata_snapshot->getSampleBlock(), context, input_function);
392 393
                    input_storage.setInputStream(input_stream);
                }
P
palasonicq 已提交
394 395 396 397 398 399
            }
        }
        else
            /// reset Input callbacks if query is not INSERT SELECT
            context.resetInputCallbacks();

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

402
        std::shared_ptr<const EnabledQuota> quota;
403 404 405
        if (!interpreter->ignoreQuota())
        {
            quota = context.getQuota();
406 407 408 409 410
            if (quota)
            {
                quota->used(Quota::QUERIES, 1);
                quota->checkExceeded(Quota::ERRORS);
            }
411 412
        }

N
Nikolai Kochetov 已提交
413
        StreamLocalLimits limits;
414 415
        if (!interpreter->ignoreLimits())
        {
416
            limits.mode = LimitsMode::LIMITS_CURRENT;
417 418 419
            limits.size_limits = SizeLimits(settings.max_result_rows, settings.max_result_bytes, settings.result_overflow_mode);
        }

N
Nikolai Kochetov 已提交
420 421 422
        res = interpreter->execute();
        QueryPipeline & pipeline = res.pipeline;
        bool use_processors = pipeline.initialized();
N
Nikolai Kochetov 已提交
423

424 425 426
        if (res.pipeline.initialized())
            use_processors = true;

A
Alexey Milovidov 已提交
427
        if (const auto * insert_interpreter = typeid_cast<const InterpreterInsertQuery *>(&*interpreter))
428 429
        {
            /// Save insertion table (not table function). TODO: support remote() table function.
430 431 432
            auto table_id = insert_interpreter->getDatabaseTable();
            if (!table_id.empty())
                context.setInsertionTable(std::move(table_id));
433
        }
434 435

        if (process_list_entry)
436 437 438 439 440
        {
            /// 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 已提交
441
            else if (!use_processors)
442 443
                (*process_list_entry)->setQueryStreams(res);
        }
444 445 446 447

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

N
Nikolai Kochetov 已提交
448
        if (use_processors)
449
        {
450 451
            /// Limits on the result, the quota on the result, and also callback for progress.
            /// Limits apply only to the final result.
452 453
            pipeline.setProgressCallback(context.getProgressCallback());
            pipeline.setProcessListElement(context.getProcessListElement());
454
            if (stage == QueryProcessingStage::Complete && !pipeline.isCompleted())
455
            {
N
Nikolai Kochetov 已提交
456
                pipeline.resize(1);
N
Nikolai Kochetov 已提交
457 458
                pipeline.addSimpleTransform([&](const Block & header)
                {
N
Nikolai Kochetov 已提交
459 460 461 462
                    auto transform = std::make_shared<LimitsCheckingTransform>(header, limits);
                    transform->setQuota(quota);
                    return transform;
                });
463 464
            }
        }
N
Nikolai Kochetov 已提交
465
        else
466
        {
467 468
            /// Limits on the result, the quota on the result, and also callback for progress.
            /// Limits apply only to the final result.
N
Nikolai Kochetov 已提交
469
            if (res.in)
470
            {
N
Nikolai Kochetov 已提交
471 472 473 474
                res.in->setProgressCallback(context.getProgressCallback());
                res.in->setProcessListElement(context.getProcessListElement());
                if (stage == QueryProcessingStage::Complete)
                {
475 476 477 478
                    if (!interpreter->ignoreQuota())
                        res.in->setQuota(quota);
                    if (!interpreter->ignoreLimits())
                        res.in->setLimits(limits);
N
Nikolai Kochetov 已提交
479 480 481 482
                }
            }

            if (res.out)
483
            {
A
Alexey Milovidov 已提交
484
                if (auto * stream = dynamic_cast<CountingBlockOutputStream *>(res.out.get()))
N
Nikolai Kochetov 已提交
485 486 487
                {
                    stream->setProcessListElement(context.getProcessListElement());
                }
488 489 490 491 492 493 494
            }
        }

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

495
            elem.type = QueryLogElementType::QUERY_START;
496 497

            elem.event_time = current_time;
498
            elem.event_time_microseconds = current_time_microseconds;
499
            elem.query_start_time = current_time;
500
            elem.query_start_time_microseconds = current_time_microseconds;
501

502
            elem.current_database = context.getCurrentDatabase();
M
Mikhail Filimonov 已提交
503
            elem.query = query_for_logging;
504 505 506 507 508 509

            elem.client_info = context.getClientInfo();

            bool log_queries = settings.log_queries && !internal;

            /// Log into system table start of query execution, if need.
510
            if (log_queries)
511
            {
512 513 514
                if (settings.log_query_settings)
                    elem.query_settings = std::make_shared<Settings>(context.getSettingsRef());

515 516 517 518 519
                if (elem.type >= settings.log_queries_min_type)
                {
                    if (auto query_log = context.getQueryLog())
                        query_log->add(elem);
                }
520
            }
521

522
            /// Common code for finish and exception callbacks
523
            auto status_info_to_query_log = [](QueryLogElement &element, const QueryStatusInfo &info, const ASTPtr query_ast) mutable
524 525 526
            {
                DB::UInt64 query_time = info.elapsed_seconds * 1000000;
                ProfileEvents::increment(ProfileEvents::QueryTimeMicroseconds, query_time);
527
                if (query_ast->as<ASTSelectQuery>() || query_ast->as<ASTSelectWithUnionQuery>())
528 529 530
                {
                    ProfileEvents::increment(ProfileEvents::SelectQueryTimeMicroseconds, query_time);
                }
531
                else if (query_ast->as<ASTInsertQuery>())
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
                {
                    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);
            };

550
            /// Also make possible for caller to log successful query finish and exception during execution.
551 552
            auto finish_callback = [elem, &context, ast, log_queries, log_queries_min_type = settings.log_queries_min_type,
                status_info_to_query_log]
553
                (IBlockInputStream * stream_in, IBlockOutputStream * stream_out, QueryPipeline * query_pipeline) mutable
554
            {
555
                QueryStatus * process_list_elem = context.getProcessListElement();
556 557 558 559

                if (!process_list_elem)
                    return;

560
                /// Update performance counters before logging to query_log
561
                CurrentThread::finalizePerformanceCounters();
562

563
                QueryStatusInfo info = process_list_elem->getInfo(true, context.getSettingsRef().log_profile_events);
564 565

                double elapsed_seconds = info.elapsed_seconds;
566

567
                elem.type = QueryLogElementType::QUERY_FINISH;
568

569 570 571 572 573
                // 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.
                const auto time_now = std::chrono::system_clock::now();
                elem.event_time = time_in_seconds(time_now);
                elem.event_time_microseconds = time_in_microseconds(time_now);
574
                status_info_to_query_log(elem, info, ast);
575

576
                auto progress_callback = context.getProgressCallback();
G
Guillaume Tassery 已提交
577

578 579 580
                if (progress_callback)
                    progress_callback(Progress(WriteProgress(info.written_rows, info.written_bytes)));

581 582
                if (stream_in)
                {
583
                    const BlockStreamProfileInfo & stream_in_info = stream_in->getProfileInfo();
584

585 586 587
                    /// NOTE: INSERT SELECT query contains zero metrics
                    elem.result_rows = stream_in_info.rows;
                    elem.result_bytes = stream_in_info.bytes;
588 589 590
                }
                else if (stream_out) /// will be used only for ordinary INSERT queries
                {
A
Alexey Milovidov 已提交
591
                    if (const auto * counting_stream = dynamic_cast<const CountingBlockOutputStream *>(stream_out))
592
                    {
M
maiha 已提交
593
                        /// NOTE: Redundancy. The same values could be extracted from process_list_elem->progress_out.query_settings = process_list_elem->progress_in
594 595
                        elem.result_rows = counting_stream->getProgress().read_rows;
                        elem.result_bytes = counting_stream->getProgress().read_bytes;
596 597
                    }
                }
598 599 600 601 602 603 604 605
                else if (query_pipeline)
                {
                    if (const auto * output_format = query_pipeline->getOutputFormat())
                    {
                        elem.result_rows = output_format->getResultRows();
                        elem.result_bytes = output_format->getResultBytes();
                    }
                }
606 607 608

                if (elem.read_rows != 0)
                {
A
Alexey Milovidov 已提交
609
                    LOG_INFO(&Poco::Logger::get("executeQuery"), "Read {} rows, {} in {} sec., {} rows/sec., {}/sec.",
610
                        elem.read_rows, ReadableSize(elem.read_bytes), elapsed_seconds,
A
Alexey Milovidov 已提交
611
                        static_cast<size_t>(elem.read_rows / elapsed_seconds),
612
                        ReadableSize(elem.read_bytes / elapsed_seconds));
613 614
                }

A
Alexey Milovidov 已提交
615
                elem.thread_ids = std::move(info.thread_ids);
616 617
                elem.profile_counters = std::move(info.profile_counters);

618
                if (log_queries && elem.type >= log_queries_min_type)
619 620 621 622
                {
                    if (auto query_log = context.getQueryLog())
                        query_log->add(elem);
                }
623 624
            };

625 626
            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
627
            {
628 629
                if (quota)
                    quota->used(Quota::ERRORS, 1, /* check_exceeded = */ false);
630

631
                elem.type = QueryLogElementType::EXCEPTION_WHILE_PROCESSING;
632

633
                // event_time and event_time_microseconds are being constructed from the same time point
634
                // to ensure that both the times will be equal upto the precision of a second.
635
                const auto time_now = std::chrono::system_clock::now();
636

637 638
                elem.event_time = time_in_seconds(time_now);
                elem.event_time_microseconds = time_in_microseconds(time_now);
639
                elem.query_duration_ms = 1000 * (elem.event_time - elem.query_start_time);
M
millb 已提交
640
                elem.exception_code = getCurrentExceptionCode();
641 642
                elem.exception = getCurrentExceptionMessage(false);

643
                QueryStatus * process_list_elem = context.getProcessListElement();
644
                const Settings & current_settings = context.getSettingsRef();
645

646
                /// Update performance counters before logging to query_log
647
                CurrentThread::finalizePerformanceCounters();
648

649 650
                if (process_list_elem)
                {
651
                    QueryStatusInfo info = process_list_elem->getInfo(true, current_settings.log_profile_events, false);
652
                    status_info_to_query_log(elem, info, ast);
653
                }
654

655
                if (current_settings.calculate_text_stack_trace)
656
                    setExceptionStackTrace(elem);
657
                logException(context, elem);
658

659
                /// In case of exception we log internal queries also
660
                if (log_queries && elem.type >= log_queries_min_type)
661 662 663 664
                {
                    if (auto query_log = context.getQueryLog())
                        query_log->add(elem);
                }
665 666

                ProfileEvents::increment(ProfileEvents::FailedQuery);
N
Nikita Orlov 已提交
667 668
                if (ast->as<ASTSelectQuery>() || ast->as<ASTSelectWithUnionQuery>())
                {
669 670
                    ProfileEvents::increment(ProfileEvents::FailedSelectQuery);
                }
N
Nikita Orlov 已提交
671 672 673 674
                else if (ast->as<ASTInsertQuery>())
                {
                    ProfileEvents::increment(ProfileEvents::FailedInsertQuery);
                }
675

676
            };
677

N
Nikolai Kochetov 已提交
678 679
            res.finish_callback = std::move(finish_callback);
            res.exception_callback = std::move(exception_callback);
N
Nikolai Kochetov 已提交
680

681 682 683 684 685
            if (!internal && res.in)
            {
                std::stringstream log_str;
                log_str << "Query pipeline:\n";
                res.in->dumpTree(log_str);
A
Alexey Milovidov 已提交
686
                LOG_DEBUG(&Poco::Logger::get("executeQuery"), log_str.str());
687 688 689 690 691 692
            }
        }
    }
    catch (...)
    {
        if (!internal)
M
Mikhail Filimonov 已提交
693 694 695 696
        {
            if (query_for_logging.empty())
                query_for_logging = prepareQueryForLogging(query, context);

697
            onExceptionBeforeStart(query_for_logging, context, current_time, current_time_microseconds, ast);
M
Mikhail Filimonov 已提交
698
        }
699 700 701 702

        throw;
    }

703
    return std::make_tuple(ast, std::move(res));
704 705 706 707
}


BlockIO executeQuery(
708 709 710
    const String & query,
    Context & context,
    bool internal,
711
    QueryProcessingStage::Enum stage,
712
    bool may_have_embedded_data)
713
{
A
Amos Bird 已提交
714
    ASTPtr ast;
715
    BlockIO streams;
A
Amos Bird 已提交
716
    std::tie(ast, streams) = executeQueryImpl(query.data(), query.data() + query.size(), context,
717
        internal, stage, !may_have_embedded_data, nullptr);
718 719

    if (const auto * ast_query_with_output = dynamic_cast<const ASTQueryWithOutput *>(ast.get()))
A
Amos Bird 已提交
720
    {
721 722 723 724
        String format_name = ast_query_with_output->format
                ? getIdentifierName(ast_query_with_output->format)
                : context.getDefaultFormat();

A
Amos Bird 已提交
725 726 727
        if (format_name == "Null")
            streams.null_format = true;
    }
728

729
    return streams;
730 731
}

N
Nikolai Kochetov 已提交
732 733 734 735 736 737 738 739
BlockIO executeQuery(
        const String & query,
        Context & context,
        bool internal,
        QueryProcessingStage::Enum stage,
        bool may_have_embedded_data,
        bool allow_processors)
{
N
Nikolai Kochetov 已提交
740
    BlockIO res = executeQuery(query, context, internal, stage, may_have_embedded_data);
N
Nikolai Kochetov 已提交
741 742 743 744 745 746 747

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

    return res;
}

748

A
Alexey Milovidov 已提交
749
void executeQuery(
750 751 752 753
    ReadBuffer & istr,
    WriteBuffer & ostr,
    bool allow_into_outfile,
    Context & context,
754
    std::function<void(const String &, const String &, const String &, const String &)> set_result_details)
A
Alexey Milovidov 已提交
755
{
756 757 758 759 760
    PODArray<char> parse_buf;
    const char * begin;
    const char * end;

    /// If 'istr' is empty now, fetch next data into buffer.
A
Alexander Kuzmenkov 已提交
761
    if (!istr.hasPendingData())
762 763 764 765
        istr.next();

    size_t max_query_size = context.getSettingsRef().max_query_size;

766
    bool may_have_tail;
N
Nikolai Kochetov 已提交
767
    if (istr.buffer().end() - istr.position() > static_cast<ssize_t>(max_query_size))
768 769 770 771 772
    {
        /// 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;
773 774 775
        /// 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;
776 777 778 779
    }
    else
    {
        /// If not - copy enough data into 'parse_buf'.
780 781 782
        WriteBufferFromVector<PODArray<char>> out(parse_buf);
        LimitReadBuffer limit(istr, max_query_size + 1, false);
        copyData(limit, out);
A
Alexander Burmak 已提交
783
        out.finalize();
784

785
        begin = parse_buf.data();
786
        end = begin + parse_buf.size();
787 788
        /// Can check stream for eof, because we have copied data
        may_have_tail = !istr.eof();
789 790 791 792 793
    }

    ASTPtr ast;
    BlockIO streams;

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

N
Nikolai Kochetov 已提交
796 797
    auto & pipeline = streams.pipeline;

798 799 800 801
    try
    {
        if (streams.out)
        {
802
            InputStreamFromASTInsertQuery in(ast, &istr, streams.out->getHeader(), context, nullptr);
803 804
            copyData(in, *streams.out);
        }
A
Amos Bird 已提交
805
        else if (streams.in)
806
        {
807 808
            /// FIXME: try to prettify this cast using `as<>()`
            const auto * ast_query_with_output = dynamic_cast<const ASTQueryWithOutput *>(ast.get());
809 810

            WriteBuffer * out_buf = &ostr;
811
            std::optional<WriteBufferFromFile> out_file_buf;
812 813 814 815 816
            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);

817
                const auto & out_file = ast_query_with_output->out_file->as<ASTLiteral &>().value.safeGet<std::string>();
818
                out_file_buf.emplace(out_file, DBMS_DEFAULT_BUFFER_SIZE, O_WRONLY | O_EXCL | O_CREAT);
819
                out_buf = &*out_file_buf;
820 821 822
            }

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

A
Alexey Milovidov 已提交
826 827
            if (ast_query_with_output && ast_query_with_output->settings_ast)
                InterpreterSetQuery(ast_query_with_output->settings_ast, context).executeForCurrentContext();
828

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

831 832
            /// Save previous progress callback if any. TODO Do it more conveniently.
            auto previous_progress_callback = context.getProgressCallback();
833

834 835 836 837 838 839 840
            /// 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);
            });
841

842 843
            if (set_result_details)
                set_result_details(context.getClientInfo().current_query_id, out->getContentType(), format_name, DateLUT::instance().getTimeZone());
844

845
            copyData(*streams.in, *out, [](){ return false; }, [&out](const Block &) { out->flush(); });
846
        }
A
Amos Bird 已提交
847
        else if (pipeline.initialized())
N
Nikolai Kochetov 已提交
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
        {
            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 已提交
864
                                 ? getIdentifierName(ast_query_with_output->format)
N
Nikolai Kochetov 已提交
865 866 867 868 869
                                 : context.getDefaultFormat();

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

870
            if (!pipeline.isCompleted())
N
Nikolai Kochetov 已提交
871
            {
872 873 874 875
                pipeline.addSimpleTransform([](const Block & header)
                {
                    return std::make_shared<MaterializingTransform>(header);
                });
N
Nikolai Kochetov 已提交
876

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

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

883 884 885 886 887 888 889
                /// 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 已提交
890

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

894 895 896 897 898 899
                pipeline.setOutputFormat(std::move(out));
            }
            else
            {
                pipeline.setProgressCallback(context.getProgressCallback());
            }
900

901
            {
N
Nikolai Kochetov 已提交
902
                auto executor = pipeline.execute();
903
                executor->execute(pipeline.getNumThreads());
904
            }
N
Nikolai Kochetov 已提交
905
        }
906 907 908 909 910 911 912 913
    }
    catch (...)
    {
        streams.onException();
        throw;
    }

    streams.onFinish();
914
}
915

A
Alexey Milovidov 已提交
916
}