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

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

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

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

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

30
#include <Access/EnabledQuota.h>
31 32 33
#include <Interpreters/InterpreterFactory.h>
#include <Interpreters/ProcessList.h>
#include <Interpreters/QueryLog.h>
34
#include <Interpreters/InterpreterSetQuery.h>
A
new  
Alexander Tretiakov 已提交
35
#include <Interpreters/ReplaceQueryParameterVisitor.h>
36
#include <Interpreters/executeQuery.h>
37
#include <Interpreters/Context.h>
M
Mikhail Filimonov 已提交
38
#include <Common/ProfileEvents.h>
39

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

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

A
Alexey Milovidov 已提交
47

M
Mikhail Filimonov 已提交
48 49 50
namespace ProfileEvents
{
    extern const Event QueryMaskingRulesMatch;
51 52 53
    extern const Event FailedQuery;
    extern const Event FailedInsertQuery;
    extern const Event FailedSelectQuery;
M
Mikhail Filimonov 已提交
54 55
}

A
Alexey Milovidov 已提交
56 57 58
namespace DB
{

59 60
namespace ErrorCodes
{
61
    extern const int INTO_OUTFILE_NOT_ALLOWED;
62
    extern const int QUERY_WAS_CANCELLED;
63 64
}

A
Alexey Milovidov 已提交
65

66
static void checkASTSizeLimits(const IAST & ast, const Settings & settings)
67
{
68 69 70 71
    if (settings.max_ast_depth)
        ast.checkDepth(settings.max_ast_depth);
    if (settings.max_ast_elements)
        ast.checkSize(settings.max_ast_elements);
72
}
73

74

75 76
static String joinLines(const String & query)
{
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
    /// Care should be taken. We don't join lines inside non-whitespace tokens (e.g. multiline string literals)
    ///  and we don't join line after single-line comment.
    /// 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);
    }

103
    return res;
104 105 106
}


M
Mikhail Filimonov 已提交
107 108 109 110
static String prepareQueryForLogging(const String & query, Context & context)
{
    String res = query;

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

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

M
Mikhail Filimonov 已提交
124 125 126 127
    return res;
}


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


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

157 158 159 160
    try
    {
        throw;
    }
161
    catch (const std::exception & e)
162
    {
163
        elem.stack_trace = getExceptionStackTraceString(e);
164 165
    }
    catch (...) {}
166 167 168 169 170 171
}


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


182
static void onExceptionBeforeStart(const String & query_for_logging, Context & context, time_t current_time, ASTPtr ast)
183
{
184
    /// Exception before the query execution.
185 186
    if (auto quota = context.getQuota())
        quota->used(Quota::ERRORS, 1, /* check_exceeded = */ false);
187

188
    const Settings & settings = context.getSettingsRef();
189

190
    /// Log the start of query execution into the table if necessary.
191
    QueryLogElement elem;
192

193
    elem.type = QueryLogElementType::EXCEPTION_BEFORE_START;
194

195 196
    elem.event_time = current_time;
    elem.query_start_time = current_time;
197

M
Mikhail Filimonov 已提交
198
    elem.query = query_for_logging;
M
millb 已提交
199
    elem.exception_code = getCurrentExceptionCode();
200
    elem.exception = getCurrentExceptionMessage(false);
201

202
    elem.client_info = context.getClientInfo();
203

204 205
    if (settings.calculate_text_stack_trace)
        setExceptionStackTrace(elem);
206
    logException(context, elem);
207

208 209 210
    /// Update performance counters before logging to query_log
    CurrentThread::finalizePerformanceCounters();

211
    if (settings.log_queries && elem.type >= settings.log_queries_min_type)
212 213
        if (auto query_log = context.getQueryLog())
            query_log->add(elem);
214 215 216 217 218 219 220 221 222 223 224 225 226 227

    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);
        }
    }
228 229
}

230 231 232 233 234
static void setQuerySpecificSettings(ASTPtr & ast, Context & context)
{
    if (auto * ast_insert_into = dynamic_cast<ASTInsertQuery *>(ast.get()))
    {
        if (ast_insert_into->watch)
235
            context.setSetting("output_format_enable_streaming", 1);
236 237
    }
}
238

239
static std::tuple<ASTPtr, BlockIO> executeQueryImpl(
240 241
    const char * begin,
    const char * end,
242 243
    Context & context,
    bool internal,
A
alesapin 已提交
244
    QueryProcessingStage::Enum stage,
245
    bool has_query_tail,
246
    ReadBuffer * istr)
247
{
248
    time_t current_time = time(nullptr);
249

250 251 252 253 254 255 256
    /// 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);
    }
257

258 259
    const Settings & settings = context.getSettingsRef();

260
    ParserQuery parser(end, settings.enable_debug_queries);
261
    ASTPtr ast;
262
    const char * query_end;
263 264 265 266 267

    /// Don't limit the size of internal queries.
    size_t max_query_size = 0;
    if (!internal)
        max_query_size = settings.max_query_size;
268 269 270

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

I
Ivan Lezhankin 已提交
274
        auto * insert_query = ast->as<ASTInsertQuery>();
Z
zhang2014 已提交
275 276 277 278

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

279
        if (insert_query && insert_query->data)
A
alesapin 已提交
280
        {
281
            query_end = insert_query->data;
A
alesapin 已提交
282 283
            insert_query->has_tail = has_query_tail;
        }
284
        else
A
Alexey Milovidov 已提交
285
        {
286
            query_end = end;
A
Alexey Milovidov 已提交
287
        }
288 289 290
    }
    catch (...)
    {
A
Alexey Milovidov 已提交
291 292
        /// Anyway log the query.
        String query = String(begin, begin + std::min(end - begin, static_cast<ptrdiff_t>(max_query_size)));
M
Mikhail Filimonov 已提交
293 294 295

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

297
        if (!internal)
298
            onExceptionBeforeStart(query_for_logging, context, current_time, ast);
299

300 301
        throw;
    }
302

303 304
    setQuerySpecificSettings(ast, context);

305 306
    /// 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);
307
    BlockIO res;
308

A
Alexey Milovidov 已提交
309
    String query_for_logging;
M
Mikhail Filimonov 已提交
310

311 312
    try
    {
A
Alexey Milovidov 已提交
313
        /// Replace ASTQueryParameter with ASTLiteral for prepared statements.
A
Merging  
Alexey Milovidov 已提交
314 315 316 317
        if (context.hasQueryParameters())
        {
            ReplaceQueryParameterVisitor visitor(context.getQueryParameters());
            visitor.visit(ast);
A
Alexey Milovidov 已提交
318

A
Alexey Milovidov 已提交
319
            /// Get new query after substitutions.
A
Alexander Tretiakov 已提交
320
            query = serializeAST(*ast);
A
Alexey Milovidov 已提交
321
        }
A
Alexander Tretiakov 已提交
322

M
Mikhail Filimonov 已提交
323 324 325
        query_for_logging = prepareQueryForLogging(query, context);

        logQuery(query_for_logging, context, internal);
326

327
        /// Check the limits.
328
        checkASTSizeLimits(*ast, settings);
329 330 331

        /// Put query to process list. But don't put SHOW PROCESSLIST query itself.
        ProcessList::EntryPtr process_list_entry;
I
Ivan Lezhankin 已提交
332
        if (!internal && !ast->as<ASTShowProcesslistQuery>())
333
        {
M
Mikhail Filimonov 已提交
334 335
            /// 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);
336 337 338
            context.setProcessListElement(&process_list_entry->get());
        }

339 340 341
        /// Load external tables if they were provided
        context.initializeExternalTablesIfSet();

P
palasonicq 已提交
342
        auto * insert_query = ast->as<ASTInsertQuery>();
343
        if (insert_query && insert_query->select)
P
palasonicq 已提交
344
        {
345
            /// Prepare Input storage before executing interpreter if we already got a buffer with data.
P
palasonicq 已提交
346 347
            if (istr)
            {
348
                ASTPtr input_function;
P
palasonicq 已提交
349
                insert_query->tryFindInputFunction(input_function);
350 351 352 353 354 355 356 357
                if (input_function)
                {
                    StoragePtr storage = context.executeTableFunction(input_function);
                    auto & input_storage = dynamic_cast<StorageInput &>(*storage);
                    BlockInputStreamPtr input_stream = std::make_shared<InputStreamFromASTInsertQuery>(ast, istr,
                        input_storage.getSampleBlock(), context, input_function);
                    input_storage.setInputStream(input_stream);
                }
P
palasonicq 已提交
358 359 360 361 362 363
            }
        }
        else
            /// reset Input callbacks if query is not INSERT SELECT
            context.resetInputCallbacks();

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

366
        std::shared_ptr<const EnabledQuota> quota;
367 368 369
        if (!interpreter->ignoreQuota())
        {
            quota = context.getQuota();
370 371 372 373 374
            if (quota)
            {
                quota->used(Quota::QUERIES, 1);
                quota->checkExceeded(Quota::ERRORS);
            }
375 376 377 378 379 380 381 382 383
        }

        IBlockInputStream::LocalLimits limits;
        if (!interpreter->ignoreLimits())
        {
            limits.mode = IBlockInputStream::LIMITS_CURRENT;
            limits.size_limits = SizeLimits(settings.max_result_rows, settings.max_result_bytes, settings.result_overflow_mode);
        }

N
Nikolai Kochetov 已提交
384 385 386
        res = interpreter->execute();
        QueryPipeline & pipeline = res.pipeline;
        bool use_processors = pipeline.initialized();
N
Nikolai Kochetov 已提交
387

388 389 390
        if (res.pipeline.initialized())
            use_processors = true;

A
Alexey Milovidov 已提交
391
        if (const auto * insert_interpreter = typeid_cast<const InterpreterInsertQuery *>(&*interpreter))
392 393
        {
            /// Save insertion table (not table function). TODO: support remote() table function.
394 395 396
            auto table_id = insert_interpreter->getDatabaseTable();
            if (!table_id.empty())
                context.setInsertionTable(std::move(table_id));
397
        }
398 399

        if (process_list_entry)
400 401 402 403 404
        {
            /// 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 已提交
405
            else if (!use_processors)
406 407
                (*process_list_entry)->setQueryStreams(res);
        }
408 409 410 411

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

N
Nikolai Kochetov 已提交
412
        if (use_processors)
413
        {
414 415
            /// Limits on the result, the quota on the result, and also callback for progress.
            /// Limits apply only to the final result.
416 417
            pipeline.setProgressCallback(context.getProgressCallback());
            pipeline.setProcessListElement(context.getProcessListElement());
418
            if (stage == QueryProcessingStage::Complete && !pipeline.isCompleted())
419
            {
N
Nikolai Kochetov 已提交
420
                pipeline.resize(1);
N
Nikolai Kochetov 已提交
421 422
                pipeline.addSimpleTransform([&](const Block & header)
                {
N
Nikolai Kochetov 已提交
423 424 425 426
                    auto transform = std::make_shared<LimitsCheckingTransform>(header, limits);
                    transform->setQuota(quota);
                    return transform;
                });
427 428
            }
        }
N
Nikolai Kochetov 已提交
429
        else
430
        {
431 432
            /// Limits on the result, the quota on the result, and also callback for progress.
            /// Limits apply only to the final result.
N
Nikolai Kochetov 已提交
433
            if (res.in)
434
            {
N
Nikolai Kochetov 已提交
435 436 437 438
                res.in->setProgressCallback(context.getProgressCallback());
                res.in->setProcessListElement(context.getProcessListElement());
                if (stage == QueryProcessingStage::Complete)
                {
439 440 441 442
                    if (!interpreter->ignoreQuota())
                        res.in->setQuota(quota);
                    if (!interpreter->ignoreLimits())
                        res.in->setLimits(limits);
N
Nikolai Kochetov 已提交
443 444 445 446
                }
            }

            if (res.out)
447
            {
A
Alexey Milovidov 已提交
448
                if (auto * stream = dynamic_cast<CountingBlockOutputStream *>(res.out.get()))
N
Nikolai Kochetov 已提交
449 450 451
                {
                    stream->setProcessListElement(context.getProcessListElement());
                }
452 453 454 455 456 457 458
            }
        }

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

459
            elem.type = QueryLogElementType::QUERY_START;
460 461 462 463

            elem.event_time = current_time;
            elem.query_start_time = current_time;

M
Mikhail Filimonov 已提交
464
            elem.query = query_for_logging;
465 466 467 468 469 470

            elem.client_info = context.getClientInfo();

            bool log_queries = settings.log_queries && !internal;

            /// Log into system table start of query execution, if need.
471
            if (log_queries && elem.type >= settings.log_queries_min_type)
472
            {
473 474 475
                if (settings.log_query_settings)
                    elem.query_settings = std::make_shared<Settings>(context.getSettingsRef());

476 477 478
                if (auto query_log = context.getQueryLog())
                    query_log->add(elem);
            }
479 480

            /// Also make possible for caller to log successful query finish and exception during execution.
481
            auto finish_callback = [elem, &context, log_queries, log_queries_min_type = settings.log_queries_min_type] (IBlockInputStream * stream_in, IBlockOutputStream * stream_out) mutable
482
            {
483
                QueryStatus * process_list_elem = context.getProcessListElement();
484 485 486 487

                if (!process_list_elem)
                    return;

488
                /// Update performance counters before logging to query_log
489
                CurrentThread::finalizePerformanceCounters();
490

491
                QueryStatusInfo info = process_list_elem->getInfo(true, context.getSettingsRef().log_profile_events);
492 493

                double elapsed_seconds = info.elapsed_seconds;
494

495
                elem.type = QueryLogElementType::QUERY_FINISH;
496

497
                elem.event_time = time(nullptr);
498 499
                elem.query_duration_ms = elapsed_seconds * 1000;

500 501
                elem.read_rows = info.read_rows;
                elem.read_bytes = info.read_bytes;
502

503 504
                elem.written_rows = info.written_rows;
                elem.written_bytes = info.written_bytes;
505

506
                auto progress_callback = context.getProgressCallback();
G
Guillaume Tassery 已提交
507

508 509 510
                if (progress_callback)
                    progress_callback(Progress(WriteProgress(info.written_rows, info.written_bytes)));

511
                elem.memory_usage = info.peak_memory_usage > 0 ? info.peak_memory_usage : 0;
512 513 514

                if (stream_in)
                {
515
                    const BlockStreamProfileInfo & stream_in_info = stream_in->getProfileInfo();
516

517 518 519
                    /// NOTE: INSERT SELECT query contains zero metrics
                    elem.result_rows = stream_in_info.rows;
                    elem.result_bytes = stream_in_info.bytes;
520 521 522
                }
                else if (stream_out) /// will be used only for ordinary INSERT queries
                {
A
Alexey Milovidov 已提交
523
                    if (const auto * counting_stream = dynamic_cast<const CountingBlockOutputStream *>(stream_out))
524
                    {
M
maiha 已提交
525
                        /// NOTE: Redundancy. The same values could be extracted from process_list_elem->progress_out.query_settings = process_list_elem->progress_in
526 527
                        elem.result_rows = counting_stream->getProgress().read_rows;
                        elem.result_bytes = counting_stream->getProgress().read_bytes;
528 529 530 531 532
                    }
                }

                if (elem.read_rows != 0)
                {
A
Alexey Milovidov 已提交
533
                    LOG_INFO(&Poco::Logger::get("executeQuery"), "Read {} rows, {} in {} sec., {} rows/sec., {}/sec.",
534
                        elem.read_rows, ReadableSize(elem.read_bytes), elapsed_seconds,
A
Alexey Milovidov 已提交
535
                        static_cast<size_t>(elem.read_rows / elapsed_seconds),
536
                        ReadableSize(elem.read_bytes / elapsed_seconds));
537 538
                }

A
Alexey Milovidov 已提交
539
                elem.thread_ids = std::move(info.thread_ids);
540 541
                elem.profile_counters = std::move(info.profile_counters);

542
                if (log_queries && elem.type >= log_queries_min_type)
543 544 545 546
                {
                    if (auto query_log = context.getQueryLog())
                        query_log->add(elem);
                }
547 548
            };

549
            auto exception_callback = [elem, &context, ast, log_queries, log_queries_min_type = settings.log_queries_min_type, quota(quota)] () mutable
550
            {
551 552
                if (quota)
                    quota->used(Quota::ERRORS, 1, /* check_exceeded = */ false);
553

554
                elem.type = QueryLogElementType::EXCEPTION_WHILE_PROCESSING;
555

556
                elem.event_time = time(nullptr);
557
                elem.query_duration_ms = 1000 * (elem.event_time - elem.query_start_time);
M
millb 已提交
558
                elem.exception_code = getCurrentExceptionCode();
559 560
                elem.exception = getCurrentExceptionMessage(false);

561
                QueryStatus * process_list_elem = context.getProcessListElement();
562
                const Settings & current_settings = context.getSettingsRef();
563

564
                /// Update performance counters before logging to query_log
565
                CurrentThread::finalizePerformanceCounters();
566

567 568
                if (process_list_elem)
                {
569
                    QueryStatusInfo info = process_list_elem->getInfo(true, current_settings.log_profile_events, false);
570

571
                    elem.query_duration_ms = info.elapsed_seconds * 1000;
572

573 574
                    elem.read_rows = info.read_rows;
                    elem.read_bytes = info.read_bytes;
575

576
                    elem.memory_usage = info.peak_memory_usage > 0 ? info.peak_memory_usage : 0;
577

A
Alexey Milovidov 已提交
578
                    elem.thread_ids = std::move(info.thread_ids);
579
                    elem.profile_counters = std::move(info.profile_counters);
580
                }
581

582
                if (current_settings.calculate_text_stack_trace)
583
                    setExceptionStackTrace(elem);
584
                logException(context, elem);
585

586
                /// In case of exception we log internal queries also
587
                if (log_queries && elem.type >= log_queries_min_type)
588 589 590 591
                {
                    if (auto query_log = context.getQueryLog())
                        query_log->add(elem);
                }
592 593

                ProfileEvents::increment(ProfileEvents::FailedQuery);
N
Nikita Orlov 已提交
594 595
                if (ast->as<ASTSelectQuery>() || ast->as<ASTSelectWithUnionQuery>())
                {
596 597
                    ProfileEvents::increment(ProfileEvents::FailedSelectQuery);
                }
N
Nikita Orlov 已提交
598 599 600 601
                else if (ast->as<ASTInsertQuery>())
                {
                    ProfileEvents::increment(ProfileEvents::FailedInsertQuery);
                }
602

603
            };
604

N
Nikolai Kochetov 已提交
605 606
            res.finish_callback = std::move(finish_callback);
            res.exception_callback = std::move(exception_callback);
N
Nikolai Kochetov 已提交
607

608 609 610 611 612
            if (!internal && res.in)
            {
                std::stringstream log_str;
                log_str << "Query pipeline:\n";
                res.in->dumpTree(log_str);
A
Alexey Milovidov 已提交
613
                LOG_DEBUG(&Poco::Logger::get("executeQuery"), log_str.str());
614 615 616 617 618 619
            }
        }
    }
    catch (...)
    {
        if (!internal)
M
Mikhail Filimonov 已提交
620 621 622 623
        {
            if (query_for_logging.empty())
                query_for_logging = prepareQueryForLogging(query, context);

624
            onExceptionBeforeStart(query_for_logging, context, current_time, ast);
M
Mikhail Filimonov 已提交
625
        }
626 627 628 629

        throw;
    }

630
    return std::make_tuple(ast, std::move(res));
631 632 633 634
}


BlockIO executeQuery(
635 636 637
    const String & query,
    Context & context,
    bool internal,
638
    QueryProcessingStage::Enum stage,
639
    bool may_have_embedded_data)
640
{
A
Amos Bird 已提交
641
    ASTPtr ast;
642
    BlockIO streams;
A
Amos Bird 已提交
643
    std::tie(ast, streams) = executeQueryImpl(query.data(), query.data() + query.size(), context,
644
        internal, stage, !may_have_embedded_data, nullptr);
645 646

    if (const auto * ast_query_with_output = dynamic_cast<const ASTQueryWithOutput *>(ast.get()))
A
Amos Bird 已提交
647
    {
648 649 650 651
        String format_name = ast_query_with_output->format
                ? getIdentifierName(ast_query_with_output->format)
                : context.getDefaultFormat();

A
Amos Bird 已提交
652 653 654
        if (format_name == "Null")
            streams.null_format = true;
    }
655

656
    return streams;
657 658
}

N
Nikolai Kochetov 已提交
659 660 661 662 663 664 665 666
BlockIO executeQuery(
        const String & query,
        Context & context,
        bool internal,
        QueryProcessingStage::Enum stage,
        bool may_have_embedded_data,
        bool allow_processors)
{
N
Nikolai Kochetov 已提交
667
    BlockIO res = executeQuery(query, context, internal, stage, may_have_embedded_data);
N
Nikolai Kochetov 已提交
668 669 670 671 672 673 674

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

    return res;
}

675

A
Alexey Milovidov 已提交
676
void executeQuery(
677 678 679 680
    ReadBuffer & istr,
    WriteBuffer & ostr,
    bool allow_into_outfile,
    Context & context,
681
    std::function<void(const String &, const String &, const String &, const String &)> set_result_details)
A
Alexey Milovidov 已提交
682
{
683 684 685 686 687 688 689 690 691 692
    PODArray<char> parse_buf;
    const char * begin;
    const char * end;

    /// If 'istr' is empty now, fetch next data into buffer.
    if (istr.buffer().size() == 0)
        istr.next();

    size_t max_query_size = context.getSettingsRef().max_query_size;

693
    bool may_have_tail;
N
Nikolai Kochetov 已提交
694
    if (istr.buffer().end() - istr.position() > static_cast<ssize_t>(max_query_size))
695 696 697 698 699
    {
        /// 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;
700 701 702
        /// 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;
703 704 705 706
    }
    else
    {
        /// If not - copy enough data into 'parse_buf'.
707 708 709
        WriteBufferFromVector<PODArray<char>> out(parse_buf);
        LimitReadBuffer limit(istr, max_query_size + 1, false);
        copyData(limit, out);
A
Alexander Burmak 已提交
710
        out.finalize();
711

712
        begin = parse_buf.data();
713
        end = begin + parse_buf.size();
714 715
        /// Can check stream for eof, because we have copied data
        may_have_tail = !istr.eof();
716 717 718 719 720
    }

    ASTPtr ast;
    BlockIO streams;

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

N
Nikolai Kochetov 已提交
723 724
    auto & pipeline = streams.pipeline;

725 726 727 728
    try
    {
        if (streams.out)
        {
729
            InputStreamFromASTInsertQuery in(ast, &istr, streams.out->getHeader(), context, nullptr);
730 731 732 733 734
            copyData(in, *streams.out);
        }

        if (streams.in)
        {
735 736
            /// FIXME: try to prettify this cast using `as<>()`
            const auto * ast_query_with_output = dynamic_cast<const ASTQueryWithOutput *>(ast.get());
737 738

            WriteBuffer * out_buf = &ostr;
739
            std::optional<WriteBufferFromFile> out_file_buf;
740 741 742 743 744
            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);

745
                const auto & out_file = ast_query_with_output->out_file->as<ASTLiteral &>().value.safeGet<std::string>();
746
                out_file_buf.emplace(out_file, DBMS_DEFAULT_BUFFER_SIZE, O_WRONLY | O_EXCL | O_CREAT);
747
                out_buf = &*out_file_buf;
748 749 750
            }

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

A
Alexey Milovidov 已提交
754 755
            if (ast_query_with_output && ast_query_with_output->settings_ast)
                InterpreterSetQuery(ast_query_with_output->settings_ast, context).executeForCurrentContext();
756

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

759 760
            /// Save previous progress callback if any. TODO Do it more conveniently.
            auto previous_progress_callback = context.getProgressCallback();
761

762 763 764 765 766 767 768
            /// 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);
            });
769

770 771
            if (set_result_details)
                set_result_details(context.getClientInfo().current_query_id, out->getContentType(), format_name, DateLUT::instance().getTimeZone());
772

773
            copyData(*streams.in, *out, [](){ return false; }, [&out](const Block &) { out->flush(); });
774
        }
N
Nikolai Kochetov 已提交
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792

        if (pipeline.initialized())
        {
            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 已提交
793
                                 ? getIdentifierName(ast_query_with_output->format)
N
Nikolai Kochetov 已提交
794 795 796 797 798
                                 : context.getDefaultFormat();

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

799
            if (!pipeline.isCompleted())
N
Nikolai Kochetov 已提交
800
            {
801 802 803 804
                pipeline.addSimpleTransform([](const Block & header)
                {
                    return std::make_shared<MaterializingTransform>(header);
                });
N
Nikolai Kochetov 已提交
805

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

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

812 813 814 815 816 817 818
                /// 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 已提交
819

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

823 824 825 826 827 828
                pipeline.setOutputFormat(std::move(out));
            }
            else
            {
                pipeline.setProgressCallback(context.getProgressCallback());
            }
829

830
            {
N
Nikolai Kochetov 已提交
831
                auto executor = pipeline.execute();
832
                executor->execute(pipeline.getNumThreads());
833
            }
N
Nikolai Kochetov 已提交
834
        }
835 836 837 838 839 840 841 842
    }
    catch (...)
    {
        streams.onException();
        throw;
    }

    streams.onFinish();
843
}
844

A
Alexey Milovidov 已提交
845
}