2011-08-28 05:13:24 +00:00
|
|
|
|
#include <DB/DataStreams/ExpressionBlockInputStream.h>
|
|
|
|
|
#include <DB/DataStreams/FilterBlockInputStream.h>
|
|
|
|
|
#include <DB/DataStreams/LimitBlockInputStream.h>
|
2011-09-04 05:14:52 +00:00
|
|
|
|
#include <DB/DataStreams/PartialSortingBlockInputStream.h>
|
|
|
|
|
#include <DB/DataStreams/MergeSortingBlockInputStream.h>
|
2015-01-18 08:27:28 +00:00
|
|
|
|
#include <DB/DataStreams/MergingSortedBlockInputStream.h>
|
2011-09-25 03:37:09 +00:00
|
|
|
|
#include <DB/DataStreams/AggregatingBlockInputStream.h>
|
2012-05-30 01:38:02 +00:00
|
|
|
|
#include <DB/DataStreams/MergingAggregatedBlockInputStream.h>
|
2011-11-28 05:51:33 +00:00
|
|
|
|
#include <DB/DataStreams/AsynchronousBlockInputStream.h>
|
2012-01-10 22:11:51 +00:00
|
|
|
|
#include <DB/DataStreams/UnionBlockInputStream.h>
|
2012-02-27 06:28:20 +00:00
|
|
|
|
#include <DB/DataStreams/ParallelAggregatingBlockInputStream.h>
|
2013-06-01 07:43:57 +00:00
|
|
|
|
#include <DB/DataStreams/DistinctBlockInputStream.h>
|
2012-05-30 04:45:49 +00:00
|
|
|
|
#include <DB/DataStreams/NullBlockInputStream.h>
|
2014-02-27 12:49:21 +00:00
|
|
|
|
#include <DB/DataStreams/TotalsHavingBlockInputStream.h>
|
2011-10-30 05:19:41 +00:00
|
|
|
|
#include <DB/DataStreams/copyData.h>
|
2014-03-04 11:26:55 +00:00
|
|
|
|
#include <DB/DataStreams/CreatingSetsBlockInputStream.h>
|
2014-12-16 10:39:02 +00:00
|
|
|
|
#include <DB/DataStreams/MaterializingBlockInputStream.h>
|
2015-04-16 06:12:35 +00:00
|
|
|
|
#include <DB/DataStreams/FormatFactory.h>
|
2011-08-28 05:13:24 +00:00
|
|
|
|
|
|
|
|
|
#include <DB/Parsers/ASTSelectQuery.h>
|
|
|
|
|
#include <DB/Parsers/ASTIdentifier.h>
|
2011-09-04 05:14:52 +00:00
|
|
|
|
#include <DB/Parsers/ASTFunction.h>
|
2011-08-28 08:02:11 +00:00
|
|
|
|
#include <DB/Parsers/ASTLiteral.h>
|
2011-09-04 05:14:52 +00:00
|
|
|
|
#include <DB/Parsers/ASTOrderByElement.h>
|
2011-08-28 05:13:24 +00:00
|
|
|
|
|
|
|
|
|
#include <DB/Interpreters/InterpreterSelectQuery.h>
|
2015-06-05 21:28:04 +00:00
|
|
|
|
#include <DB/Interpreters/InterpreterSetQuery.h>
|
2015-05-06 23:35:37 +00:00
|
|
|
|
#include <DB/Interpreters/ExpressionAnalyzer.h>
|
2013-10-30 13:52:02 +00:00
|
|
|
|
#include <DB/Storages/StorageView.h>
|
2014-01-28 16:45:10 +00:00
|
|
|
|
#include <DB/TableFunctions/ITableFunction.h>
|
|
|
|
|
#include <DB/TableFunctions/TableFunctionFactory.h>
|
2011-08-28 05:13:24 +00:00
|
|
|
|
|
2014-01-28 19:26:39 +00:00
|
|
|
|
#include <DB/Core/Field.h>
|
|
|
|
|
|
2011-08-28 05:13:24 +00:00
|
|
|
|
namespace DB
|
|
|
|
|
{
|
|
|
|
|
|
2015-05-06 23:35:37 +00:00
|
|
|
|
InterpreterSelectQuery::~InterpreterSelectQuery() = default;
|
|
|
|
|
|
|
|
|
|
|
2014-12-24 12:59:02 +00:00
|
|
|
|
void InterpreterSelectQuery::init(BlockInputStreamPtr input, const Names & required_column_names, const NamesAndTypesList & table_column_names)
|
2014-12-26 10:35:03 +00:00
|
|
|
|
{
|
|
|
|
|
ProfileEvents::increment(ProfileEvents::SelectQuery);
|
|
|
|
|
|
2015-06-05 21:28:04 +00:00
|
|
|
|
initSettings();
|
|
|
|
|
|
|
|
|
|
original_max_threads = settings.max_threads;
|
|
|
|
|
|
2014-12-26 10:35:03 +00:00
|
|
|
|
if (settings.limits.max_subquery_depth && subquery_depth > settings.limits.max_subquery_depth)
|
|
|
|
|
throw Exception("Too deep subqueries. Maximum: " + toString(settings.limits.max_subquery_depth),
|
|
|
|
|
ErrorCodes::TOO_DEEP_SUBQUERIES);
|
|
|
|
|
|
2015-02-13 11:40:58 +00:00
|
|
|
|
if (is_first_select_inside_union_all)
|
|
|
|
|
{
|
|
|
|
|
/// Создать цепочку запросов SELECT.
|
|
|
|
|
InterpreterSelectQuery * interpreter = this;
|
|
|
|
|
ASTPtr tail = query.next_union_all;
|
|
|
|
|
query.next_union_all = nullptr;
|
|
|
|
|
|
|
|
|
|
while (!tail.isNull())
|
|
|
|
|
{
|
|
|
|
|
ASTPtr head = tail;
|
|
|
|
|
|
|
|
|
|
ASTSelectQuery & head_query = static_cast<ASTSelectQuery &>(*head);
|
|
|
|
|
tail = head_query.next_union_all;
|
|
|
|
|
head_query.next_union_all = nullptr;
|
|
|
|
|
|
|
|
|
|
interpreter->next_select_in_union_all.reset(new InterpreterSelectQuery(head, context, to_stage, subquery_depth, nullptr, false));
|
|
|
|
|
interpreter = interpreter->next_select_in_union_all.get();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (is_first_select_inside_union_all && hasAsterisk())
|
2014-12-24 12:59:02 +00:00
|
|
|
|
{
|
2014-12-25 10:22:24 +00:00
|
|
|
|
basicInit(input, table_column_names);
|
2014-12-25 14:17:08 +00:00
|
|
|
|
|
|
|
|
|
// Мы выполняем этот код именно здесь, потому что в противном случае следующего рода запрос бы не срабатывал:
|
|
|
|
|
// SELECT X FROM (SELECT * FROM (SELECT 1 AS X, 2 AS Y) UNION ALL SELECT 3, 4)
|
|
|
|
|
// из-за того, что астериски заменены столбцами только при создании объектов query_analyzer в basicInit().
|
|
|
|
|
renameColumns();
|
|
|
|
|
|
2014-12-24 14:05:55 +00:00
|
|
|
|
if (!required_column_names.empty() && (context.getColumns().size() != required_column_names.size()))
|
|
|
|
|
{
|
|
|
|
|
rewriteExpressionList(required_column_names);
|
2014-12-24 15:13:00 +00:00
|
|
|
|
/// Теперь имеется устаревшая информация для выполнения запроса. Обновляем эту информацию.
|
2014-12-25 10:22:24 +00:00
|
|
|
|
initQueryAnalyzer();
|
2014-12-24 14:05:55 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
2014-12-25 14:17:08 +00:00
|
|
|
|
renameColumns();
|
2014-12-24 14:05:55 +00:00
|
|
|
|
if (!required_column_names.empty())
|
|
|
|
|
rewriteExpressionList(required_column_names);
|
2014-12-25 14:17:08 +00:00
|
|
|
|
|
2014-12-25 10:22:24 +00:00
|
|
|
|
basicInit(input, table_column_names);
|
2014-12-24 12:59:02 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
2014-12-25 10:22:24 +00:00
|
|
|
|
void InterpreterSelectQuery::basicInit(BlockInputStreamPtr input_, const NamesAndTypesList & table_column_names)
|
2014-12-24 12:59:02 +00:00
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
if (query.table && typeid_cast<ASTSelectQuery *>(&*query.table))
|
|
|
|
|
{
|
|
|
|
|
if (table_column_names.empty())
|
2014-12-25 14:43:53 +00:00
|
|
|
|
{
|
2015-01-03 03:18:49 +00:00
|
|
|
|
/// Оптимизация: мы считаем, что запрос содержит только один SELECT, даже если это может быть
|
2014-12-25 15:29:22 +00:00
|
|
|
|
/// в самом деле цепочкой UNION ALL. Первый запрос достаточен для определения нужных столбцов.
|
2014-12-25 14:43:53 +00:00
|
|
|
|
context.setColumns(InterpreterSelectQuery(query.table, context, to_stage, subquery_depth, nullptr, false).getSampleBlock().getColumnsList());
|
|
|
|
|
}
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
if (query.table && typeid_cast<const ASTFunction *>(&*query.table))
|
|
|
|
|
{
|
|
|
|
|
/// Получить табличную функцию
|
|
|
|
|
TableFunctionPtr table_function_ptr = context.getTableFunctionFactory().get(typeid_cast<const ASTFunction *>(&*query.table)->name, context);
|
|
|
|
|
/// Выполнить ее и запомнить результат
|
|
|
|
|
storage = table_function_ptr->execute(query.table, context);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
String database_name;
|
|
|
|
|
String table_name;
|
|
|
|
|
|
|
|
|
|
getDatabaseAndTableNames(database_name, table_name);
|
|
|
|
|
|
|
|
|
|
storage = context.getTable(database_name, table_name);
|
|
|
|
|
}
|
|
|
|
|
|
2015-01-16 15:22:12 +00:00
|
|
|
|
if (!storage->supportsParallelReplicas() && (settings.parallel_replicas_count > 0))
|
2015-01-29 14:22:15 +00:00
|
|
|
|
throw Exception("Storage engine " + storage->getName()
|
2015-01-16 15:22:12 +00:00
|
|
|
|
+ " does not support parallel execution on several replicas",
|
|
|
|
|
ErrorCodes::STORAGE_DOESNT_SUPPORT_PARALLEL_REPLICAS);
|
|
|
|
|
|
2014-12-19 12:48:09 +00:00
|
|
|
|
table_lock = storage->lockStructure(false);
|
|
|
|
|
if (table_column_names.empty())
|
|
|
|
|
context.setColumns(storage->getColumnsListNonMaterialized());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!table_column_names.empty())
|
|
|
|
|
context.setColumns(table_column_names);
|
|
|
|
|
|
|
|
|
|
if (context.getColumns().empty())
|
|
|
|
|
throw Exception("There are no available columns", ErrorCodes::THERE_IS_NO_COLUMN);
|
|
|
|
|
|
2015-01-14 02:44:25 +00:00
|
|
|
|
query_analyzer.reset(new ExpressionAnalyzer(query_ptr, context, storage, subquery_depth, true));
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
|
|
|
|
/// Сохраняем в query context новые временные таблицы
|
|
|
|
|
for (auto & it : query_analyzer->getExternalTables())
|
|
|
|
|
if (!context.tryGetExternalTable(it.first))
|
|
|
|
|
context.addExternalTable(it.first, it.second);
|
|
|
|
|
|
2014-12-24 14:51:02 +00:00
|
|
|
|
if (input_)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
streams.push_back(input_);
|
2014-12-23 15:33:36 +00:00
|
|
|
|
|
2015-02-13 11:40:58 +00:00
|
|
|
|
if (is_first_select_inside_union_all)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2015-02-13 11:40:58 +00:00
|
|
|
|
/// Проверяем, что результаты всех запросов SELECT cовместимые.
|
|
|
|
|
Block first = getSampleBlock();
|
|
|
|
|
for (auto p = next_select_in_union_all.get(); p != nullptr; p = p->next_select_in_union_all.get())
|
2014-12-25 14:43:53 +00:00
|
|
|
|
{
|
2015-02-13 11:40:58 +00:00
|
|
|
|
Block current = p->getSampleBlock();
|
2014-12-25 14:43:53 +00:00
|
|
|
|
if (!blocksHaveEqualStructure(first, current))
|
|
|
|
|
throw Exception("Result structures mismatch in the SELECT queries of the UNION ALL chain. Found result structure:\n\n" + current.dumpStructure()
|
2015-01-03 03:18:49 +00:00
|
|
|
|
+ "\n\nwhile expecting:\n\n" + first.dumpStructure() + "\n\ninstead",
|
2014-12-25 14:43:53 +00:00
|
|
|
|
ErrorCodes::UNION_ALL_RESULT_STRUCTURES_MISMATCH);
|
|
|
|
|
}
|
2014-12-23 15:33:36 +00:00
|
|
|
|
}
|
2014-12-24 14:51:02 +00:00
|
|
|
|
}
|
|
|
|
|
|
2014-12-25 10:22:24 +00:00
|
|
|
|
void InterpreterSelectQuery::initQueryAnalyzer()
|
2014-12-24 14:51:02 +00:00
|
|
|
|
{
|
2015-01-14 02:44:25 +00:00
|
|
|
|
query_analyzer.reset(new ExpressionAnalyzer(query_ptr, context, storage, subquery_depth, true));
|
2014-12-24 14:51:02 +00:00
|
|
|
|
for (auto p = next_select_in_union_all.get(); p != nullptr; p = p->next_select_in_union_all.get())
|
2015-01-14 02:44:25 +00:00
|
|
|
|
p->query_analyzer.reset(new ExpressionAnalyzer(p->query_ptr, p->context, p->storage, p->subquery_depth, true));
|
2014-12-23 15:33:36 +00:00
|
|
|
|
}
|
|
|
|
|
|
2013-11-08 17:43:03 +00:00
|
|
|
|
InterpreterSelectQuery::InterpreterSelectQuery(ASTPtr query_ptr_, const Context & context_, QueryProcessingStage::Enum to_stage_,
|
2014-12-19 12:48:09 +00:00
|
|
|
|
size_t subquery_depth_, BlockInputStreamPtr input_, bool is_union_all_head_)
|
|
|
|
|
: query_ptr(query_ptr_), query(typeid_cast<ASTSelectQuery &>(*query_ptr)),
|
2015-06-05 21:28:04 +00:00
|
|
|
|
context(context_), to_stage(to_stage_), subquery_depth(subquery_depth_),
|
2015-02-13 11:40:58 +00:00
|
|
|
|
is_first_select_inside_union_all(is_union_all_head_ && !query.next_union_all.isNull()),
|
2014-12-19 12:48:09 +00:00
|
|
|
|
log(&Logger::get("InterpreterSelectQuery"))
|
2013-11-08 17:43:03 +00:00
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
init(input_);
|
2011-08-28 05:13:24 +00:00
|
|
|
|
}
|
|
|
|
|
|
2014-06-12 23:21:38 +00:00
|
|
|
|
InterpreterSelectQuery::InterpreterSelectQuery(ASTPtr query_ptr_, const Context & context_,
|
2014-12-19 12:48:09 +00:00
|
|
|
|
const Names & required_column_names_,
|
|
|
|
|
QueryProcessingStage::Enum to_stage_, size_t subquery_depth_, BlockInputStreamPtr input_)
|
|
|
|
|
: query_ptr(query_ptr_), query(typeid_cast<ASTSelectQuery &>(*query_ptr)),
|
2015-06-05 21:28:04 +00:00
|
|
|
|
context(context_), to_stage(to_stage_), subquery_depth(subquery_depth_),
|
2015-02-13 11:40:58 +00:00
|
|
|
|
is_first_select_inside_union_all(!query.next_union_all.isNull()),
|
2014-12-19 12:48:09 +00:00
|
|
|
|
log(&Logger::get("InterpreterSelectQuery"))
|
2013-11-08 17:43:03 +00:00
|
|
|
|
{
|
2014-12-24 12:59:02 +00:00
|
|
|
|
init(input_, required_column_names_);
|
2014-02-08 16:49:45 +00:00
|
|
|
|
}
|
|
|
|
|
|
2014-06-12 23:21:38 +00:00
|
|
|
|
InterpreterSelectQuery::InterpreterSelectQuery(ASTPtr query_ptr_, const Context & context_,
|
2014-12-19 12:48:09 +00:00
|
|
|
|
const Names & required_column_names_,
|
|
|
|
|
const NamesAndTypesList & table_column_names, QueryProcessingStage::Enum to_stage_, size_t subquery_depth_, BlockInputStreamPtr input_)
|
|
|
|
|
: query_ptr(query_ptr_), query(typeid_cast<ASTSelectQuery &>(*query_ptr)),
|
2015-06-05 21:28:04 +00:00
|
|
|
|
context(context_), to_stage(to_stage_), subquery_depth(subquery_depth_),
|
2015-02-13 11:40:58 +00:00
|
|
|
|
is_first_select_inside_union_all(!query.next_union_all.isNull()),
|
2014-12-19 12:48:09 +00:00
|
|
|
|
log(&Logger::get("InterpreterSelectQuery"))
|
2015-01-03 03:18:49 +00:00
|
|
|
|
{
|
2014-12-24 12:59:02 +00:00
|
|
|
|
init(input_, required_column_names_, table_column_names);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
2014-12-16 10:39:02 +00:00
|
|
|
|
|
2014-12-25 14:17:08 +00:00
|
|
|
|
bool InterpreterSelectQuery::hasAsterisk() const
|
|
|
|
|
{
|
|
|
|
|
if (query.hasAsterisk())
|
|
|
|
|
return true;
|
|
|
|
|
|
2015-02-13 11:40:58 +00:00
|
|
|
|
if (is_first_select_inside_union_all)
|
|
|
|
|
for (auto p = next_select_in_union_all.get(); p != nullptr; p = p->next_select_in_union_all.get())
|
2014-12-25 14:43:53 +00:00
|
|
|
|
{
|
2015-02-13 11:40:58 +00:00
|
|
|
|
if (p->query.hasAsterisk())
|
2014-12-25 14:43:53 +00:00
|
|
|
|
return true;
|
|
|
|
|
}
|
2015-01-03 03:18:49 +00:00
|
|
|
|
|
2014-12-25 14:17:08 +00:00
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void InterpreterSelectQuery::renameColumns()
|
|
|
|
|
{
|
2015-02-13 11:40:58 +00:00
|
|
|
|
if (is_first_select_inside_union_all)
|
|
|
|
|
for (auto p = next_select_in_union_all.get(); p != nullptr; p = p->next_select_in_union_all.get())
|
|
|
|
|
p->query.renameColumns(query);
|
2014-12-25 14:17:08 +00:00
|
|
|
|
}
|
|
|
|
|
|
2014-12-19 12:48:09 +00:00
|
|
|
|
void InterpreterSelectQuery::rewriteExpressionList(const Names & required_column_names)
|
|
|
|
|
{
|
|
|
|
|
if (query.distinct)
|
|
|
|
|
return;
|
2015-01-03 03:18:49 +00:00
|
|
|
|
|
2015-02-13 11:40:58 +00:00
|
|
|
|
if (is_first_select_inside_union_all)
|
|
|
|
|
for (auto p = next_select_in_union_all.get(); p != nullptr; p = p->next_select_in_union_all.get())
|
2014-12-25 14:43:53 +00:00
|
|
|
|
{
|
2015-02-13 11:40:58 +00:00
|
|
|
|
if (p->query.distinct)
|
2014-12-25 14:43:53 +00:00
|
|
|
|
return;
|
|
|
|
|
}
|
2015-01-03 03:18:49 +00:00
|
|
|
|
|
2014-12-19 12:48:09 +00:00
|
|
|
|
query.rewriteSelectExpressionList(required_column_names);
|
2015-01-03 03:18:49 +00:00
|
|
|
|
|
2015-02-13 11:40:58 +00:00
|
|
|
|
if (is_first_select_inside_union_all)
|
|
|
|
|
for (auto p = next_select_in_union_all.get(); p != nullptr; p = p->next_select_in_union_all.get())
|
|
|
|
|
p->query.rewriteSelectExpressionList(required_column_names);
|
2013-11-08 17:43:03 +00:00
|
|
|
|
}
|
2011-08-28 05:13:24 +00:00
|
|
|
|
|
2012-08-20 19:21:04 +00:00
|
|
|
|
void InterpreterSelectQuery::getDatabaseAndTableNames(String & database_name, String & table_name)
|
2011-08-28 05:13:24 +00:00
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
/** Если таблица не указана - используем таблицу system.one.
|
|
|
|
|
* Если база данных не указана - используем текущую базу данных.
|
|
|
|
|
*/
|
|
|
|
|
if (query.database)
|
|
|
|
|
database_name = typeid_cast<ASTIdentifier &>(*query.database).name;
|
|
|
|
|
if (query.table)
|
|
|
|
|
table_name = typeid_cast<ASTIdentifier &>(*query.table).name;
|
|
|
|
|
|
|
|
|
|
if (!query.table)
|
|
|
|
|
{
|
|
|
|
|
database_name = "system";
|
|
|
|
|
table_name = "one";
|
|
|
|
|
}
|
|
|
|
|
else if (!query.database)
|
|
|
|
|
{
|
|
|
|
|
if (context.tryGetTable("", table_name))
|
|
|
|
|
database_name = "";
|
|
|
|
|
else
|
|
|
|
|
database_name = context.getCurrentDatabase();
|
|
|
|
|
}
|
2012-08-20 19:21:04 +00:00
|
|
|
|
}
|
|
|
|
|
|
2011-08-28 05:13:24 +00:00
|
|
|
|
|
|
|
|
|
DataTypes InterpreterSelectQuery::getReturnTypes()
|
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
DataTypes res;
|
|
|
|
|
NamesAndTypesList columns = query_analyzer->getSelectSampleBlock().getColumnsList();
|
2015-05-06 23:35:37 +00:00
|
|
|
|
for (auto & column : columns)
|
|
|
|
|
res.push_back(column.type);
|
|
|
|
|
|
2014-12-19 12:48:09 +00:00
|
|
|
|
return res;
|
2011-08-28 05:13:24 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2011-10-30 05:19:41 +00:00
|
|
|
|
Block InterpreterSelectQuery::getSampleBlock()
|
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
Block block = query_analyzer->getSelectSampleBlock();
|
|
|
|
|
/// создадим ненулевые колонки, чтобы SampleBlock можно было
|
|
|
|
|
/// писать (читать) с помощью BlockOut(In)putStream'ов
|
|
|
|
|
for (size_t i = 0; i < block.columns(); ++i)
|
|
|
|
|
{
|
|
|
|
|
ColumnWithNameAndType & col = block.getByPosition(i);
|
|
|
|
|
col.column = col.type->createColumn();
|
|
|
|
|
}
|
|
|
|
|
return block;
|
2011-10-30 05:19:41 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2015-06-18 02:11:05 +00:00
|
|
|
|
BlockIO InterpreterSelectQuery::execute()
|
2014-12-19 15:56:12 +00:00
|
|
|
|
{
|
2015-04-21 15:12:08 +00:00
|
|
|
|
(void) executeWithoutUnion();
|
2015-01-03 03:18:49 +00:00
|
|
|
|
|
2014-12-19 15:56:12 +00:00
|
|
|
|
if (streams.empty())
|
2015-06-18 02:11:05 +00:00
|
|
|
|
{
|
|
|
|
|
BlockIO res;
|
|
|
|
|
res.in = new NullBlockInputStream;
|
|
|
|
|
res.in_sample = getSampleBlock();
|
|
|
|
|
return res;
|
|
|
|
|
}
|
2015-01-03 03:18:49 +00:00
|
|
|
|
|
2014-12-19 15:56:12 +00:00
|
|
|
|
executeUnion(streams);
|
2015-01-03 03:18:49 +00:00
|
|
|
|
|
2014-12-19 12:48:09 +00:00
|
|
|
|
/// Ограничения на результат, квота на результат, а также колбек для прогресса.
|
|
|
|
|
if (IProfilingBlockInputStream * stream = dynamic_cast<IProfilingBlockInputStream *>(&*streams[0]))
|
|
|
|
|
{
|
|
|
|
|
stream->setProgressCallback(context.getProgressCallback());
|
|
|
|
|
stream->setProcessListElement(context.getProcessListElement());
|
|
|
|
|
|
|
|
|
|
/// Ограничения действуют только на конечный результат.
|
|
|
|
|
if (to_stage == QueryProcessingStage::Complete)
|
|
|
|
|
{
|
|
|
|
|
IProfilingBlockInputStream::LocalLimits limits;
|
|
|
|
|
limits.mode = IProfilingBlockInputStream::LIMITS_CURRENT;
|
|
|
|
|
limits.max_rows_to_read = settings.limits.max_result_rows;
|
|
|
|
|
limits.max_bytes_to_read = settings.limits.max_result_bytes;
|
|
|
|
|
limits.read_overflow_mode = settings.limits.result_overflow_mode;
|
|
|
|
|
|
|
|
|
|
stream->setLimits(limits);
|
|
|
|
|
stream->setQuota(context.getQuota());
|
|
|
|
|
}
|
|
|
|
|
}
|
2015-01-03 03:18:49 +00:00
|
|
|
|
|
2015-06-18 02:11:05 +00:00
|
|
|
|
BlockIO res;
|
|
|
|
|
res.in = streams[0];
|
|
|
|
|
res.in_sample = getSampleBlock();
|
|
|
|
|
|
|
|
|
|
return res;
|
2014-12-16 10:39:02 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-04-23 13:16:42 +00:00
|
|
|
|
const BlockInputStreams & InterpreterSelectQuery::executeWithoutUnion()
|
2014-12-19 15:56:12 +00:00
|
|
|
|
{
|
2015-02-13 11:40:58 +00:00
|
|
|
|
if (is_first_select_inside_union_all)
|
2014-12-19 15:56:12 +00:00
|
|
|
|
{
|
2014-12-26 21:37:38 +00:00
|
|
|
|
executeSingleQuery();
|
2014-12-19 15:56:12 +00:00
|
|
|
|
for (auto p = next_select_in_union_all.get(); p != nullptr; p = p->next_select_in_union_all.get())
|
|
|
|
|
{
|
2014-12-26 21:37:38 +00:00
|
|
|
|
p->executeSingleQuery();
|
2014-12-19 15:56:12 +00:00
|
|
|
|
const auto & others = p->streams;
|
|
|
|
|
streams.insert(streams.end(), others.begin(), others.end());
|
|
|
|
|
}
|
2015-01-03 03:18:49 +00:00
|
|
|
|
|
2014-12-19 15:56:12 +00:00
|
|
|
|
for (auto & stream : streams)
|
|
|
|
|
stream = new MaterializingBlockInputStream(stream);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
executeSingleQuery();
|
2015-01-03 03:18:49 +00:00
|
|
|
|
|
2014-12-19 15:56:12 +00:00
|
|
|
|
return streams;
|
|
|
|
|
}
|
2014-12-16 10:39:02 +00:00
|
|
|
|
|
2014-12-26 21:37:38 +00:00
|
|
|
|
void InterpreterSelectQuery::executeSingleQuery()
|
2011-08-28 05:13:24 +00:00
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
/** Потоки данных. При параллельном выполнении запроса, имеем несколько потоков данных.
|
|
|
|
|
* Если нет GROUP BY, то выполним все операции до ORDER BY и LIMIT параллельно, затем
|
|
|
|
|
* если есть ORDER BY, то склеим потоки с помощью UnionBlockInputStream, а затем MergеSortingBlockInputStream,
|
|
|
|
|
* если нет, то склеим с помощью UnionBlockInputStream,
|
|
|
|
|
* затем применим LIMIT.
|
|
|
|
|
* Если есть GROUP BY, то выполним все операции до GROUP BY, включительно, параллельно;
|
|
|
|
|
* параллельный GROUP BY склеит потоки в один,
|
|
|
|
|
* затем выполним остальные операции с одним получившимся потоком.
|
2015-01-03 03:18:49 +00:00
|
|
|
|
* Если запрос является членом цепочки UNION ALL и не содержит GROUP BY, ORDER BY, DISTINCT, или LIMIT,
|
2014-12-19 12:48:09 +00:00
|
|
|
|
* то объединение источников данных выполняется не на этом уровне, а на верхнем уровне.
|
|
|
|
|
*/
|
|
|
|
|
|
2015-04-21 15:12:08 +00:00
|
|
|
|
union_within_single_query = false;
|
2015-01-03 03:18:49 +00:00
|
|
|
|
|
2014-12-19 12:48:09 +00:00
|
|
|
|
/** Вынем данные из Storage. from_stage - до какой стадии запрос был выполнен в Storage. */
|
|
|
|
|
QueryProcessingStage::Enum from_stage = executeFetchColumns(streams);
|
|
|
|
|
|
|
|
|
|
LOG_TRACE(log, QueryProcessingStage::toString(from_stage) << " -> " << QueryProcessingStage::toString(to_stage));
|
|
|
|
|
|
|
|
|
|
if (to_stage > QueryProcessingStage::FetchColumns)
|
|
|
|
|
{
|
|
|
|
|
bool has_where = false;
|
|
|
|
|
bool need_aggregate = false;
|
|
|
|
|
bool has_having = false;
|
|
|
|
|
bool has_order_by = false;
|
2015-01-03 03:18:49 +00:00
|
|
|
|
|
2014-12-19 12:48:09 +00:00
|
|
|
|
ExpressionActionsPtr array_join;
|
|
|
|
|
ExpressionActionsPtr before_where;
|
|
|
|
|
ExpressionActionsPtr before_aggregation;
|
|
|
|
|
ExpressionActionsPtr before_having;
|
|
|
|
|
ExpressionActionsPtr before_order_and_select;
|
|
|
|
|
ExpressionActionsPtr final_projection;
|
|
|
|
|
|
|
|
|
|
/// Столбцы из списка SELECT, до переименования в алиасы.
|
|
|
|
|
Names selected_columns;
|
|
|
|
|
|
|
|
|
|
/// Нужно ли выполнять первую часть конвейера - выполняемую на удаленных серверах при распределенной обработке.
|
|
|
|
|
bool first_stage = from_stage < QueryProcessingStage::WithMergeableState
|
|
|
|
|
&& to_stage >= QueryProcessingStage::WithMergeableState;
|
|
|
|
|
/// Нужно ли выполнять вторую часть конвейера - выполняемую на сервере-инициаторе при распределенной обработке.
|
|
|
|
|
bool second_stage = from_stage <= QueryProcessingStage::WithMergeableState
|
|
|
|
|
&& to_stage > QueryProcessingStage::WithMergeableState;
|
|
|
|
|
|
|
|
|
|
/** Сначала составим цепочку действий и запомним нужные шаги из нее.
|
|
|
|
|
* Независимо от from_stage и to_stage составим полную последовательность действий, чтобы выполнять оптимизации и
|
|
|
|
|
* выбрасывать ненужные столбцы с учетом всего запроса. В ненужных частях запроса не будем выполнять подзапросы.
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
{
|
|
|
|
|
ExpressionActionsChain chain;
|
|
|
|
|
|
|
|
|
|
need_aggregate = query_analyzer->hasAggregation();
|
|
|
|
|
|
|
|
|
|
query_analyzer->appendArrayJoin(chain, !first_stage);
|
|
|
|
|
query_analyzer->appendJoin(chain, !first_stage);
|
|
|
|
|
|
|
|
|
|
if (query_analyzer->appendWhere(chain, !first_stage))
|
|
|
|
|
{
|
|
|
|
|
has_where = true;
|
|
|
|
|
before_where = chain.getLastActions();
|
|
|
|
|
chain.addStep();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (need_aggregate)
|
|
|
|
|
{
|
|
|
|
|
query_analyzer->appendGroupBy(chain, !first_stage);
|
|
|
|
|
query_analyzer->appendAggregateFunctionsArguments(chain, !first_stage);
|
|
|
|
|
before_aggregation = chain.getLastActions();
|
|
|
|
|
|
|
|
|
|
chain.finalize();
|
|
|
|
|
chain.clear();
|
|
|
|
|
|
|
|
|
|
if (query_analyzer->appendHaving(chain, !second_stage))
|
|
|
|
|
{
|
|
|
|
|
has_having = true;
|
|
|
|
|
before_having = chain.getLastActions();
|
|
|
|
|
chain.addStep();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Если есть агрегация, выполняем выражения в SELECT и ORDER BY на инициировавшем сервере, иначе - на серверах-источниках.
|
|
|
|
|
query_analyzer->appendSelect(chain, need_aggregate ? !second_stage : !first_stage);
|
|
|
|
|
selected_columns = chain.getLastStep().required_output;
|
|
|
|
|
has_order_by = query_analyzer->appendOrderBy(chain, need_aggregate ? !second_stage : !first_stage);
|
|
|
|
|
before_order_and_select = chain.getLastActions();
|
|
|
|
|
chain.addStep();
|
|
|
|
|
|
|
|
|
|
query_analyzer->appendProjectResult(chain, !second_stage);
|
|
|
|
|
final_projection = chain.getLastActions();
|
|
|
|
|
|
|
|
|
|
chain.finalize();
|
|
|
|
|
chain.clear();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Если данных нет.
|
|
|
|
|
* Эта проверка специально вынесена чуть ниже, чем она могла бы быть (сразу после executeFetchColumns),
|
|
|
|
|
* чтобы запрос был проанализирован, и в нём могли бы быть обнаружены ошибки (например, несоответствия типов).
|
|
|
|
|
* Иначе мог бы вернуться пустой результат на некорректный запрос.
|
|
|
|
|
*/
|
|
|
|
|
if (streams.empty())
|
|
|
|
|
return;
|
|
|
|
|
|
|
|
|
|
/// Перед выполнением HAVING уберем из блока лишние столбцы (в основном, ключи агрегации).
|
|
|
|
|
if (has_having)
|
|
|
|
|
before_having->prependProjectInput();
|
|
|
|
|
|
|
|
|
|
/// Теперь составим потоки блоков, выполняющие нужные действия.
|
|
|
|
|
|
|
|
|
|
/// Нужно ли агрегировать в отдельную строку строки, не прошедшие max_rows_to_group_by.
|
|
|
|
|
bool aggregate_overflow_row =
|
|
|
|
|
need_aggregate &&
|
|
|
|
|
query.group_by_with_totals &&
|
|
|
|
|
settings.limits.max_rows_to_group_by &&
|
|
|
|
|
settings.limits.group_by_overflow_mode == OverflowMode::ANY &&
|
|
|
|
|
settings.totals_mode != TotalsMode::AFTER_HAVING_EXCLUSIVE;
|
2015-02-01 08:02:18 +00:00
|
|
|
|
|
2014-12-19 12:48:09 +00:00
|
|
|
|
/// Нужно ли после агрегации сразу финализировать агрегатные функции.
|
|
|
|
|
bool aggregate_final =
|
|
|
|
|
need_aggregate &&
|
|
|
|
|
to_stage > QueryProcessingStage::WithMergeableState &&
|
|
|
|
|
!query.group_by_with_totals;
|
|
|
|
|
|
|
|
|
|
if (first_stage)
|
|
|
|
|
{
|
|
|
|
|
if (has_where)
|
|
|
|
|
executeWhere(streams, before_where);
|
|
|
|
|
|
|
|
|
|
if (need_aggregate)
|
|
|
|
|
executeAggregation(streams, before_aggregation, aggregate_overflow_row, aggregate_final);
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
executeExpression(streams, before_order_and_select);
|
|
|
|
|
executeDistinct(streams, true, selected_columns);
|
|
|
|
|
}
|
|
|
|
|
|
2015-01-18 08:27:28 +00:00
|
|
|
|
/** При распределённой обработке запроса,
|
|
|
|
|
* если не указаны GROUP, HAVING,
|
|
|
|
|
* но есть ORDER или LIMIT,
|
|
|
|
|
* то выполним предварительную сортировку и LIMIT на удалёном сервере.
|
|
|
|
|
*/
|
2014-12-19 12:48:09 +00:00
|
|
|
|
if (!second_stage
|
2015-01-18 08:27:28 +00:00
|
|
|
|
&& !need_aggregate && !has_having)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2015-01-18 08:27:28 +00:00
|
|
|
|
if (has_order_by)
|
|
|
|
|
executeOrder(streams);
|
|
|
|
|
|
|
|
|
|
if (query.limit_length)
|
|
|
|
|
executePreLimit(streams);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2015-01-03 03:18:49 +00:00
|
|
|
|
|
2014-12-19 12:48:09 +00:00
|
|
|
|
if (second_stage)
|
|
|
|
|
{
|
2015-05-05 14:02:57 +00:00
|
|
|
|
bool need_second_distinct_pass = query.distinct;
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
|
|
|
|
if (need_aggregate)
|
|
|
|
|
{
|
|
|
|
|
/// Если нужно объединить агрегированные результаты с нескольких серверов
|
|
|
|
|
if (!first_stage)
|
|
|
|
|
executeMergeAggregated(streams, aggregate_overflow_row, aggregate_final);
|
|
|
|
|
|
|
|
|
|
if (!aggregate_final)
|
|
|
|
|
executeTotalsAndHaving(streams, has_having, before_having, aggregate_overflow_row);
|
|
|
|
|
else if (has_having)
|
|
|
|
|
executeHaving(streams, before_having);
|
|
|
|
|
|
|
|
|
|
executeExpression(streams, before_order_and_select);
|
|
|
|
|
executeDistinct(streams, true, selected_columns);
|
|
|
|
|
|
2015-05-05 14:02:57 +00:00
|
|
|
|
need_second_distinct_pass = query.distinct && (streams.size() > 1);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
|
|
|
|
else if (query.group_by_with_totals && !aggregate_final)
|
|
|
|
|
{
|
|
|
|
|
executeTotalsAndHaving(streams, false, nullptr, aggregate_overflow_row);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (has_order_by)
|
2015-01-18 08:27:28 +00:00
|
|
|
|
{
|
|
|
|
|
/** Если при распределённой обработке запроса есть ORDER BY,
|
|
|
|
|
* но нет агрегации, то на удалённых серверах был сделан ORDER BY
|
|
|
|
|
* - поэтому, делаем merge сортированных потоков с удалённых серверов.
|
|
|
|
|
*/
|
|
|
|
|
if (!first_stage && !need_aggregate && !(query.group_by_with_totals && !aggregate_final))
|
|
|
|
|
executeMergeSorted(streams);
|
|
|
|
|
else /// Иначе просто сортировка.
|
|
|
|
|
executeOrder(streams);
|
|
|
|
|
}
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
|
|
|
|
executeProjection(streams, final_projection);
|
|
|
|
|
|
|
|
|
|
/// На этой стадии можно считать минимумы и максимумы, если надо.
|
|
|
|
|
if (settings.extremes)
|
2015-01-13 00:36:26 +00:00
|
|
|
|
for (auto & stream : streams)
|
|
|
|
|
if (IProfilingBlockInputStream * p_stream = dynamic_cast<IProfilingBlockInputStream *>(&*stream))
|
|
|
|
|
p_stream->enableExtremes();
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
|
|
|
|
/** Оптимизация - если источников несколько и есть LIMIT, то сначала применим предварительный LIMIT,
|
|
|
|
|
* ограничивающий число записей в каждом до offset + limit.
|
|
|
|
|
*/
|
|
|
|
|
if (query.limit_length && streams.size() > 1 && !query.distinct)
|
|
|
|
|
executePreLimit(streams);
|
2015-01-03 03:18:49 +00:00
|
|
|
|
|
2015-05-05 14:02:57 +00:00
|
|
|
|
if (need_second_distinct_pass)
|
|
|
|
|
union_within_single_query = true;
|
|
|
|
|
|
2015-04-21 15:12:08 +00:00
|
|
|
|
if (union_within_single_query)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
executeUnion(streams);
|
2015-01-03 03:18:49 +00:00
|
|
|
|
|
2015-04-21 15:12:08 +00:00
|
|
|
|
if (streams.size() == 1)
|
|
|
|
|
{
|
|
|
|
|
/// Если было более одного источника - то нужно выполнить DISTINCT ещё раз после их слияния.
|
|
|
|
|
if (need_second_distinct_pass)
|
|
|
|
|
executeDistinct(streams, false, Names());
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
2015-04-21 15:12:08 +00:00
|
|
|
|
executeLimit(streams);
|
|
|
|
|
}
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Если данных нет. */
|
|
|
|
|
if (streams.empty())
|
|
|
|
|
return;
|
|
|
|
|
|
|
|
|
|
SubqueriesForSets subqueries_for_sets = query_analyzer->getSubqueriesForSets();
|
|
|
|
|
if (!subqueries_for_sets.empty())
|
|
|
|
|
executeSubqueriesInSetsAndJoins(streams, subqueries_for_sets);
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
|
|
|
|
|
2011-08-28 05:13:24 +00:00
|
|
|
|
|
2012-05-09 13:12:38 +00:00
|
|
|
|
static void getLimitLengthAndOffset(ASTSelectQuery & query, size_t & length, size_t & offset)
|
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
length = 0;
|
|
|
|
|
offset = 0;
|
|
|
|
|
if (query.limit_length)
|
|
|
|
|
{
|
|
|
|
|
length = safeGet<UInt64>(typeid_cast<ASTLiteral &>(*query.limit_length).value);
|
|
|
|
|
if (query.limit_offset)
|
|
|
|
|
offset = safeGet<UInt64>(typeid_cast<ASTLiteral &>(*query.limit_offset).value);
|
|
|
|
|
}
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
QueryProcessingStage::Enum InterpreterSelectQuery::executeFetchColumns(BlockInputStreams & streams)
|
2012-05-09 13:12:38 +00:00
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
if (!streams.empty())
|
|
|
|
|
return QueryProcessingStage::FetchColumns;
|
|
|
|
|
|
|
|
|
|
/// Интерпретатор подзапроса, если подзапрос
|
|
|
|
|
SharedPtr<InterpreterSelectQuery> interpreter_subquery;
|
|
|
|
|
|
|
|
|
|
/// Список столбцов, которых нужно прочитать, чтобы выполнить запрос.
|
|
|
|
|
Names required_columns = query_analyzer->getRequiredColumns();
|
|
|
|
|
|
|
|
|
|
if (query.table && typeid_cast<ASTSelectQuery *>(&*query.table))
|
2015-01-03 03:18:49 +00:00
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
/** Для подзапроса не действуют ограничения на максимальный размер результата.
|
|
|
|
|
* Так как результат поздапроса - ещё не результат всего запроса.
|
|
|
|
|
*/
|
|
|
|
|
Context subquery_context = context;
|
|
|
|
|
Settings subquery_settings = context.getSettings();
|
|
|
|
|
subquery_settings.limits.max_result_rows = 0;
|
|
|
|
|
subquery_settings.limits.max_result_bytes = 0;
|
|
|
|
|
/// Вычисление extremes не имеет смысла и не нужно (если его делать, то в результате всего запроса могут взяться extremes подзапроса).
|
|
|
|
|
subquery_settings.extremes = 0;
|
|
|
|
|
subquery_context.setSettings(subquery_settings);
|
|
|
|
|
|
|
|
|
|
interpreter_subquery = new InterpreterSelectQuery(
|
|
|
|
|
query.table, subquery_context, required_columns, QueryProcessingStage::Complete, subquery_depth + 1);
|
2015-04-30 13:00:56 +00:00
|
|
|
|
|
|
|
|
|
/// Если во внешнем запросе есть аггрегация, то WITH TOTALS игнорируется в подзапросе.
|
2015-04-23 11:07:15 +00:00
|
|
|
|
if (query_analyzer->hasAggregation())
|
|
|
|
|
interpreter_subquery->ignoreWithTotals();
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// если в настройках установлен default_sample != 1, то все запросы выполняем с сэмплингом
|
|
|
|
|
/// если таблица не поддерживает сэмплинг получим исключение
|
|
|
|
|
/// поэтому запросы типа SHOW TABLES работать с включенном default_sample не будут
|
|
|
|
|
if (!query.sample_size && settings.default_sample != 1)
|
|
|
|
|
query.sample_size = new ASTLiteral(StringRange(), Float64(settings.default_sample));
|
|
|
|
|
|
|
|
|
|
if (query.sample_size && (!storage || !storage->supportsSampling()))
|
|
|
|
|
throw Exception("Illegal SAMPLE: table doesn't support sampling", ErrorCodes::SAMPLING_NOT_SUPPORTED);
|
|
|
|
|
|
|
|
|
|
if (query.final && (!storage || !storage->supportsFinal()))
|
|
|
|
|
throw Exception(storage ? "Storage " + storage->getName() + " doesn't support FINAL" : "Illegal FINAL", ErrorCodes::ILLEGAL_FINAL);
|
|
|
|
|
|
|
|
|
|
if (query.prewhere_expression && (!storage || !storage->supportsPrewhere()))
|
|
|
|
|
throw Exception(storage ? "Storage " + storage->getName() + " doesn't support PREWHERE" : "Illegal PREWHERE", ErrorCodes::ILLEGAL_PREWHERE);
|
|
|
|
|
|
|
|
|
|
/** При распределённой обработке запроса, в потоках почти не делается вычислений,
|
|
|
|
|
* а делается ожидание и получение данных с удалённых серверов.
|
|
|
|
|
* Если у нас 20 удалённых серверов, а max_threads = 8, то было бы не очень хорошо
|
|
|
|
|
* соединяться и опрашивать только по 8 серверов одновременно.
|
|
|
|
|
* Чтобы одновременно опрашивалось больше удалённых серверов,
|
|
|
|
|
* вместо max_threads используется max_distributed_connections.
|
|
|
|
|
*
|
|
|
|
|
* Сохраним изначальное значение max_threads в settings_for_storage
|
|
|
|
|
* - эти настройки будут переданы на удалённые серверы при распределённой обработке запроса,
|
|
|
|
|
* и там должно быть оригинальное значение max_threads, а не увеличенное.
|
|
|
|
|
*/
|
2015-05-11 00:11:22 +00:00
|
|
|
|
bool is_remote = false;
|
2014-12-19 12:48:09 +00:00
|
|
|
|
Settings settings_for_storage = settings;
|
|
|
|
|
if (storage && storage->isRemote())
|
2015-05-11 00:11:22 +00:00
|
|
|
|
{
|
|
|
|
|
is_remote = true;
|
2014-12-19 12:48:09 +00:00
|
|
|
|
settings.max_threads = settings.max_distributed_connections;
|
2015-05-11 00:11:22 +00:00
|
|
|
|
}
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
|
|
|
|
/// Ограничение на количество столбцов для чтения.
|
|
|
|
|
if (settings.limits.max_columns_to_read && required_columns.size() > settings.limits.max_columns_to_read)
|
|
|
|
|
throw Exception("Limit for number of columns to read exceeded. "
|
|
|
|
|
"Requested: " + toString(required_columns.size())
|
|
|
|
|
+ ", maximum: " + toString(settings.limits.max_columns_to_read),
|
|
|
|
|
ErrorCodes::TOO_MUCH_COLUMNS);
|
|
|
|
|
|
|
|
|
|
size_t limit_length = 0;
|
|
|
|
|
size_t limit_offset = 0;
|
|
|
|
|
getLimitLengthAndOffset(query, limit_length, limit_offset);
|
|
|
|
|
|
|
|
|
|
/** Оптимизация - если не указаны DISTINCT, WHERE, GROUP, HAVING, ORDER, но указан LIMIT, и limit + offset < max_block_size,
|
|
|
|
|
* то в качестве размера блока будем использовать limit + offset (чтобы не читать из таблицы больше, чем запрошено),
|
2015-05-11 00:11:22 +00:00
|
|
|
|
* а также установим количество потоков в 1.
|
2014-12-19 12:48:09 +00:00
|
|
|
|
*/
|
2015-03-15 08:05:28 +00:00
|
|
|
|
if (!query.distinct
|
|
|
|
|
&& !query.prewhere_expression
|
|
|
|
|
&& !query.where_expression
|
|
|
|
|
&& !query.group_expression_list
|
|
|
|
|
&& !query.having_expression
|
|
|
|
|
&& !query.order_expression_list
|
|
|
|
|
&& query.limit_length
|
|
|
|
|
&& !query_analyzer->hasAggregation()
|
|
|
|
|
&& limit_length + limit_offset < settings.max_block_size)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
|
|
|
|
settings.max_block_size = limit_length + limit_offset;
|
|
|
|
|
settings.max_threads = 1;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
QueryProcessingStage::Enum from_stage = QueryProcessingStage::FetchColumns;
|
|
|
|
|
|
|
|
|
|
query_analyzer->makeSetsForIndex();
|
|
|
|
|
|
|
|
|
|
/// Инициализируем изначальные потоки данных, на которые накладываются преобразования запроса. Таблица или подзапрос?
|
|
|
|
|
if (!interpreter_subquery)
|
|
|
|
|
{
|
2015-05-11 00:11:22 +00:00
|
|
|
|
size_t max_streams = settings.max_threads;
|
|
|
|
|
|
|
|
|
|
/// Если надо - запрашиваем больше источников, чем количество потоков - для более равномерного распределения работы по потокам.
|
|
|
|
|
if (max_streams > 1 && !is_remote)
|
|
|
|
|
max_streams *= settings.max_streams_to_max_threads_ratio;
|
|
|
|
|
|
2014-12-16 15:46:26 +00:00
|
|
|
|
streams = storage->read(required_columns, query_ptr,
|
2014-12-19 12:48:09 +00:00
|
|
|
|
context, settings_for_storage, from_stage,
|
2015-05-11 00:11:22 +00:00
|
|
|
|
settings.max_block_size, max_streams);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
|
|
|
|
for (auto & stream : streams)
|
|
|
|
|
stream->addTableLock(table_lock);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
2015-04-23 13:16:42 +00:00
|
|
|
|
const auto & subquery_streams = interpreter_subquery->executeWithoutUnion();
|
2015-04-23 13:09:43 +00:00
|
|
|
|
streams.insert(streams.end(), subquery_streams.begin(), subquery_streams.end());
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Установка ограничений и квоты на чтение данных, скорость и время выполнения запроса.
|
|
|
|
|
* Такие ограничения проверяются на сервере-инициаторе запроса, а не на удалённых серверах.
|
|
|
|
|
* Потому что сервер-инициатор имеет суммарные данные о выполнении запроса на всех серверах.
|
|
|
|
|
*/
|
|
|
|
|
if (storage && to_stage == QueryProcessingStage::Complete)
|
|
|
|
|
{
|
|
|
|
|
IProfilingBlockInputStream::LocalLimits limits;
|
|
|
|
|
limits.mode = IProfilingBlockInputStream::LIMITS_TOTAL;
|
|
|
|
|
limits.max_rows_to_read = settings.limits.max_rows_to_read;
|
|
|
|
|
limits.max_bytes_to_read = settings.limits.max_bytes_to_read;
|
|
|
|
|
limits.read_overflow_mode = settings.limits.read_overflow_mode;
|
|
|
|
|
limits.max_execution_time = settings.limits.max_execution_time;
|
|
|
|
|
limits.timeout_overflow_mode = settings.limits.timeout_overflow_mode;
|
|
|
|
|
limits.min_execution_speed = settings.limits.min_execution_speed;
|
|
|
|
|
limits.timeout_before_checking_execution_speed = settings.limits.timeout_before_checking_execution_speed;
|
|
|
|
|
|
|
|
|
|
QuotaForIntervals & quota = context.getQuota();
|
|
|
|
|
|
2015-01-13 00:36:26 +00:00
|
|
|
|
for (auto & stream : streams)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2015-01-13 00:36:26 +00:00
|
|
|
|
if (IProfilingBlockInputStream * p_stream = dynamic_cast<IProfilingBlockInputStream *>(&*stream))
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2015-01-13 00:36:26 +00:00
|
|
|
|
p_stream->setLimits(limits);
|
|
|
|
|
p_stream->setQuota(quota);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return from_stage;
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
2011-08-28 05:13:24 +00:00
|
|
|
|
|
2012-05-09 13:12:38 +00:00
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
void InterpreterSelectQuery::executeWhere(BlockInputStreams & streams, ExpressionActionsPtr expression)
|
2012-08-27 05:13:14 +00:00
|
|
|
|
{
|
2015-01-13 00:36:26 +00:00
|
|
|
|
for (auto & stream : streams)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2015-01-13 00:36:26 +00:00
|
|
|
|
stream = new ExpressionBlockInputStream(stream, expression);
|
|
|
|
|
stream = new FilterBlockInputStream(stream, query.where_expression->getColumnName());
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
2012-08-27 05:13:14 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2014-02-27 12:49:21 +00:00
|
|
|
|
void InterpreterSelectQuery::executeAggregation(BlockInputStreams & streams, ExpressionActionsPtr expression, bool overflow_row, bool final)
|
2012-05-09 13:12:38 +00:00
|
|
|
|
{
|
2015-01-13 00:36:26 +00:00
|
|
|
|
for (auto & stream : streams)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2015-01-13 00:36:26 +00:00
|
|
|
|
stream = new ExpressionBlockInputStream(stream, expression);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
BlockInputStreamPtr & stream = streams[0];
|
|
|
|
|
|
|
|
|
|
Names key_names;
|
|
|
|
|
AggregateDescriptions aggregates;
|
|
|
|
|
query_analyzer->getAggregateInfo(key_names, aggregates);
|
|
|
|
|
|
|
|
|
|
/// Если источников несколько, то выполняем параллельную агрегацию
|
|
|
|
|
if (streams.size() > 1)
|
|
|
|
|
{
|
2015-01-13 00:36:26 +00:00
|
|
|
|
stream = new ParallelAggregatingBlockInputStream(streams, key_names, aggregates, overflow_row, final,
|
2015-01-13 00:08:36 +00:00
|
|
|
|
settings.max_threads, settings.limits.max_rows_to_group_by, settings.limits.group_by_overflow_mode,
|
2015-02-22 05:51:16 +00:00
|
|
|
|
settings.compile ? &context.getCompiler() : nullptr, settings.min_count_to_compile, settings.group_by_two_level_threshold);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
|
|
|
|
streams.resize(1);
|
|
|
|
|
}
|
|
|
|
|
else
|
2015-01-13 00:36:26 +00:00
|
|
|
|
stream = new AggregatingBlockInputStream(stream, key_names, aggregates, overflow_row, final,
|
2015-01-10 02:30:03 +00:00
|
|
|
|
settings.limits.max_rows_to_group_by, settings.limits.group_by_overflow_mode,
|
2015-02-22 05:51:16 +00:00
|
|
|
|
settings.compile ? &context.getCompiler() : nullptr, settings.min_count_to_compile, 0);
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
2011-11-06 22:00:39 +00:00
|
|
|
|
|
2012-05-09 13:12:38 +00:00
|
|
|
|
|
2014-02-27 12:49:21 +00:00
|
|
|
|
void InterpreterSelectQuery::executeMergeAggregated(BlockInputStreams & streams, bool overflow_row, bool final)
|
2012-05-30 01:38:02 +00:00
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
/// Склеим несколько источников в один
|
2015-01-22 20:56:40 +00:00
|
|
|
|
executeUnion(streams);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
|
|
|
|
/// Теперь объединим агрегированные блоки
|
|
|
|
|
Names key_names;
|
|
|
|
|
AggregateDescriptions aggregates;
|
|
|
|
|
query_analyzer->getAggregateInfo(key_names, aggregates);
|
2015-01-13 00:36:26 +00:00
|
|
|
|
streams[0] = new MergingAggregatedBlockInputStream(streams[0], key_names, aggregates, overflow_row, final, original_max_threads);
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
void InterpreterSelectQuery::executeHaving(BlockInputStreams & streams, ExpressionActionsPtr expression)
|
2012-05-09 13:12:38 +00:00
|
|
|
|
{
|
2015-01-13 00:36:26 +00:00
|
|
|
|
for (auto & stream : streams)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2015-01-13 00:36:26 +00:00
|
|
|
|
stream = new ExpressionBlockInputStream(stream, expression);
|
|
|
|
|
stream = new FilterBlockInputStream(stream, query.having_expression->getColumnName());
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
|
|
|
|
|
2011-09-25 03:37:09 +00:00
|
|
|
|
|
2014-02-27 12:49:21 +00:00
|
|
|
|
void InterpreterSelectQuery::executeTotalsAndHaving(BlockInputStreams & streams, bool has_having,
|
2014-12-19 18:33:30 +00:00
|
|
|
|
ExpressionActionsPtr expression, bool overflow_row)
|
2014-02-27 12:49:21 +00:00
|
|
|
|
{
|
2015-01-22 20:56:40 +00:00
|
|
|
|
executeUnion(streams);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
|
|
|
|
Names key_names;
|
|
|
|
|
AggregateDescriptions aggregates;
|
|
|
|
|
query_analyzer->getAggregateInfo(key_names, aggregates);
|
2015-01-13 00:36:26 +00:00
|
|
|
|
streams[0] = new TotalsHavingBlockInputStream(
|
2014-12-19 12:48:09 +00:00
|
|
|
|
streams[0], key_names, aggregates, overflow_row, expression,
|
2015-01-13 00:36:26 +00:00
|
|
|
|
has_having ? query.having_expression->getColumnName() : "", settings.totals_mode, settings.totals_auto_threshold);
|
2014-02-27 12:49:21 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2014-03-14 08:30:50 +00:00
|
|
|
|
void InterpreterSelectQuery::executeExpression(BlockInputStreams & streams, ExpressionActionsPtr expression)
|
2012-05-09 13:12:38 +00:00
|
|
|
|
{
|
2015-01-13 00:36:26 +00:00
|
|
|
|
for (auto & stream : streams)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2015-01-13 00:36:26 +00:00
|
|
|
|
stream = new ExpressionBlockInputStream(stream, expression);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2015-01-18 08:27:28 +00:00
|
|
|
|
static SortDescription getSortDescription(ASTSelectQuery & query)
|
2012-05-09 13:12:38 +00:00
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
SortDescription order_descr;
|
|
|
|
|
order_descr.reserve(query.order_expression_list->children.size());
|
2015-03-12 03:31:15 +00:00
|
|
|
|
for (const auto & elem : query.order_expression_list->children)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2015-03-12 03:31:15 +00:00
|
|
|
|
String name = elem->children.front()->getColumnName();
|
|
|
|
|
const ASTOrderByElement & order_by_elem = typeid_cast<const ASTOrderByElement &>(*elem);
|
2015-01-07 15:30:11 +00:00
|
|
|
|
|
|
|
|
|
order_descr.emplace_back(name, order_by_elem.direction, order_by_elem.collator);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-01-18 08:27:28 +00:00
|
|
|
|
return order_descr;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static size_t getLimitForSorting(ASTSelectQuery & query)
|
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
/// Если есть LIMIT и нет DISTINCT - можно делать частичную сортировку.
|
|
|
|
|
size_t limit = 0;
|
|
|
|
|
if (!query.distinct)
|
|
|
|
|
{
|
|
|
|
|
size_t limit_length = 0;
|
|
|
|
|
size_t limit_offset = 0;
|
|
|
|
|
getLimitLengthAndOffset(query, limit_length, limit_offset);
|
|
|
|
|
limit = limit_length + limit_offset;
|
|
|
|
|
}
|
|
|
|
|
|
2015-01-18 08:27:28 +00:00
|
|
|
|
return limit;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
void InterpreterSelectQuery::executeOrder(BlockInputStreams & streams)
|
|
|
|
|
{
|
|
|
|
|
SortDescription order_descr = getSortDescription(query);
|
|
|
|
|
size_t limit = getLimitForSorting(query);
|
|
|
|
|
|
2015-01-13 00:36:26 +00:00
|
|
|
|
for (auto & stream : streams)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
|
|
|
|
IProfilingBlockInputStream * sorting_stream = new PartialSortingBlockInputStream(stream, order_descr, limit);
|
|
|
|
|
|
|
|
|
|
/// Ограничения на сортировку
|
|
|
|
|
IProfilingBlockInputStream::LocalLimits limits;
|
|
|
|
|
limits.mode = IProfilingBlockInputStream::LIMITS_TOTAL;
|
|
|
|
|
limits.max_rows_to_read = settings.limits.max_rows_to_sort;
|
|
|
|
|
limits.max_bytes_to_read = settings.limits.max_bytes_to_sort;
|
|
|
|
|
limits.read_overflow_mode = settings.limits.sort_overflow_mode;
|
|
|
|
|
sorting_stream->setLimits(limits);
|
|
|
|
|
|
2015-01-13 00:36:26 +00:00
|
|
|
|
stream = sorting_stream;
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
BlockInputStreamPtr & stream = streams[0];
|
|
|
|
|
|
|
|
|
|
/// Если потоков несколько, то объединяем их в один
|
2015-01-22 20:56:40 +00:00
|
|
|
|
executeUnion(streams);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
2015-01-07 17:19:23 +00:00
|
|
|
|
/// Сливаем сортированные блоки.
|
2015-01-13 00:36:26 +00:00
|
|
|
|
stream = new MergeSortingBlockInputStream(
|
2015-01-07 17:19:23 +00:00
|
|
|
|
stream, order_descr, settings.max_block_size, limit,
|
2015-05-28 03:49:28 +00:00
|
|
|
|
settings.limits.max_bytes_before_external_sort, context.getTemporaryPath());
|
2013-06-03 10:18:41 +00:00
|
|
|
|
}
|
2012-02-27 06:28:20 +00:00
|
|
|
|
|
2012-07-25 20:29:22 +00:00
|
|
|
|
|
2015-01-18 08:27:28 +00:00
|
|
|
|
void InterpreterSelectQuery::executeMergeSorted(BlockInputStreams & streams)
|
|
|
|
|
{
|
|
|
|
|
SortDescription order_descr = getSortDescription(query);
|
|
|
|
|
size_t limit = getLimitForSorting(query);
|
|
|
|
|
|
|
|
|
|
BlockInputStreamPtr & stream = streams[0];
|
|
|
|
|
|
|
|
|
|
/// Если потоков несколько, то объединяем их в один
|
|
|
|
|
if (streams.size() > 1)
|
|
|
|
|
{
|
|
|
|
|
/** MergingSortedBlockInputStream читает источники последовательно.
|
|
|
|
|
* Чтобы данные на удалённых серверах готовились параллельно, оборачиваем в AsynchronousBlockInputStream.
|
|
|
|
|
*/
|
|
|
|
|
for (auto & stream : streams)
|
|
|
|
|
stream = new AsynchronousBlockInputStream(stream);
|
|
|
|
|
|
|
|
|
|
/// Сливаем сортированные источники в один сортированный источник.
|
|
|
|
|
stream = new MergingSortedBlockInputStream(streams, order_descr, settings.max_block_size, limit);
|
|
|
|
|
streams.resize(1);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
void InterpreterSelectQuery::executeProjection(BlockInputStreams & streams, ExpressionActionsPtr expression)
|
|
|
|
|
{
|
2015-01-13 00:36:26 +00:00
|
|
|
|
for (auto & stream : streams)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2015-01-13 00:36:26 +00:00
|
|
|
|
stream = new ExpressionBlockInputStream(stream, expression);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
|
|
|
|
|
2012-02-27 06:28:20 +00:00
|
|
|
|
|
2014-03-28 15:57:06 +00:00
|
|
|
|
void InterpreterSelectQuery::executeDistinct(BlockInputStreams & streams, bool before_order, Names columns)
|
2013-06-01 07:43:57 +00:00
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
if (query.distinct)
|
|
|
|
|
{
|
|
|
|
|
size_t limit_length = 0;
|
|
|
|
|
size_t limit_offset = 0;
|
|
|
|
|
getLimitLengthAndOffset(query, limit_length, limit_offset);
|
|
|
|
|
|
|
|
|
|
size_t limit_for_distinct = 0;
|
|
|
|
|
|
|
|
|
|
/// Если после этой стадии DISTINCT не будет выполняться ORDER BY, то можно достать не более limit_length + limit_offset различных строк.
|
|
|
|
|
if (!query.order_expression_list || !before_order)
|
|
|
|
|
limit_for_distinct = limit_length + limit_offset;
|
|
|
|
|
|
2015-01-13 00:36:26 +00:00
|
|
|
|
for (auto & stream : streams)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2015-01-13 00:36:26 +00:00
|
|
|
|
stream = new DistinctBlockInputStream(stream, settings.limits, limit_for_distinct, columns);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
2015-04-21 22:28:42 +00:00
|
|
|
|
|
|
|
|
|
if (streams.size() > 1)
|
|
|
|
|
union_within_single_query = true;
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
2013-06-01 07:43:57 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
void InterpreterSelectQuery::executeUnion(BlockInputStreams & streams)
|
2012-05-09 13:12:38 +00:00
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
/// Если до сих пор есть несколько потоков, то объединяем их в один
|
|
|
|
|
if (streams.size() > 1)
|
|
|
|
|
{
|
|
|
|
|
streams[0] = new UnionBlockInputStream(streams, settings.max_threads);
|
|
|
|
|
streams.resize(1);
|
2015-04-21 15:12:08 +00:00
|
|
|
|
union_within_single_query = false;
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2012-06-24 23:17:06 +00:00
|
|
|
|
/// Предварительный LIMIT - применяется в каждом источнике, если источников несколько, до их объединения.
|
2013-06-03 10:18:41 +00:00
|
|
|
|
void InterpreterSelectQuery::executePreLimit(BlockInputStreams & streams)
|
2012-05-09 13:12:38 +00:00
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
size_t limit_length = 0;
|
|
|
|
|
size_t limit_offset = 0;
|
|
|
|
|
getLimitLengthAndOffset(query, limit_length, limit_offset);
|
|
|
|
|
|
|
|
|
|
/// Если есть LIMIT
|
|
|
|
|
if (query.limit_length)
|
|
|
|
|
{
|
2015-01-13 00:36:26 +00:00
|
|
|
|
for (auto & stream : streams)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
|
|
|
|
stream = new LimitBlockInputStream(stream, limit_length + limit_offset, 0);
|
|
|
|
|
}
|
2015-04-21 22:28:42 +00:00
|
|
|
|
|
2015-04-21 15:12:08 +00:00
|
|
|
|
if (streams.size() > 1)
|
|
|
|
|
union_within_single_query = true;
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
2012-06-24 23:17:06 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
void InterpreterSelectQuery::executeLimit(BlockInputStreams & streams)
|
2012-06-24 23:17:06 +00:00
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
size_t limit_length = 0;
|
|
|
|
|
size_t limit_offset = 0;
|
|
|
|
|
getLimitLengthAndOffset(query, limit_length, limit_offset);
|
|
|
|
|
|
|
|
|
|
/// Если есть LIMIT
|
|
|
|
|
if (query.limit_length)
|
|
|
|
|
{
|
|
|
|
|
BlockInputStreamPtr & stream = streams[0];
|
|
|
|
|
stream = new LimitBlockInputStream(stream, limit_length, limit_offset);
|
|
|
|
|
}
|
2011-08-28 05:13:24 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2014-07-06 19:48:39 +00:00
|
|
|
|
void InterpreterSelectQuery::executeSubqueriesInSetsAndJoins(BlockInputStreams & streams, SubqueriesForSets & subqueries_for_sets)
|
2014-03-04 11:26:55 +00:00
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
/// Если запрос не распределённый, то удалим создание временных таблиц из подзапросов (предназначавшихся для отправки на удалённые серверы).
|
|
|
|
|
if (!(storage && storage->isRemote()))
|
|
|
|
|
for (auto & elem : subqueries_for_sets)
|
|
|
|
|
elem.second.table.reset();
|
2014-07-06 21:59:20 +00:00
|
|
|
|
|
2015-01-22 20:56:40 +00:00
|
|
|
|
executeUnion(streams);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
streams[0] = new CreatingSetsBlockInputStream(streams[0], subqueries_for_sets, settings.limits);
|
2014-03-04 11:26:55 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2015-05-06 23:35:37 +00:00
|
|
|
|
void InterpreterSelectQuery::ignoreWithTotals()
|
|
|
|
|
{
|
|
|
|
|
query.group_by_with_totals = false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2015-06-05 21:28:04 +00:00
|
|
|
|
void InterpreterSelectQuery::initSettings()
|
|
|
|
|
{
|
|
|
|
|
if (query.settings)
|
|
|
|
|
InterpreterSetQuery(query.settings, context).executeForCurrentContext();
|
|
|
|
|
|
|
|
|
|
settings = context.getSettings();
|
|
|
|
|
}
|
|
|
|
|
|
2011-08-28 05:13:24 +00:00
|
|
|
|
}
|