2016-05-28 12:22:22 +00:00
|
|
|
|
#include <experimental/optional>
|
|
|
|
|
|
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>
|
2015-07-30 23:41:02 +00:00
|
|
|
|
#include <DB/DataStreams/MergingAggregatedMemoryEfficientBlockInputStream.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-07-22 01:46:35 +00:00
|
|
|
|
#include <DB/DataStreams/ConcatBlockInputStream.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>
|
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>
|
2016-11-20 12:43:20 +00:00
|
|
|
|
#include <DB/Common/Collator.h>
|
2014-01-28 19:26:39 +00:00
|
|
|
|
|
2015-10-29 15:14:19 +00:00
|
|
|
|
|
2016-10-24 02:02:37 +00:00
|
|
|
|
namespace ProfileEvents
|
|
|
|
|
{
|
|
|
|
|
extern const Event SelectQuery;
|
|
|
|
|
}
|
|
|
|
|
|
2011-08-28 05:13:24 +00:00
|
|
|
|
namespace DB
|
|
|
|
|
{
|
|
|
|
|
|
2016-01-11 21:46:36 +00:00
|
|
|
|
namespace ErrorCodes
|
|
|
|
|
{
|
|
|
|
|
extern const int TOO_DEEP_SUBQUERIES;
|
|
|
|
|
extern const int THERE_IS_NO_COLUMN;
|
|
|
|
|
extern const int UNION_ALL_RESULT_STRUCTURES_MISMATCH;
|
|
|
|
|
extern const int SAMPLING_NOT_SUPPORTED;
|
|
|
|
|
extern const int ILLEGAL_FINAL;
|
|
|
|
|
extern const int ILLEGAL_PREWHERE;
|
|
|
|
|
extern const int TOO_MUCH_COLUMNS;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2015-05-06 23:35:37 +00:00
|
|
|
|
InterpreterSelectQuery::~InterpreterSelectQuery() = default;
|
|
|
|
|
|
|
|
|
|
|
2015-07-15 01:26:35 +00:00
|
|
|
|
void InterpreterSelectQuery::init(BlockInputStreamPtr input, const Names & required_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;
|
|
|
|
|
|
2016-05-28 15:46:03 +00:00
|
|
|
|
while (tail)
|
2015-02-13 11:40:58 +00:00
|
|
|
|
{
|
|
|
|
|
ASTPtr head = tail;
|
|
|
|
|
|
|
|
|
|
ASTSelectQuery & head_query = static_cast<ASTSelectQuery &>(*head);
|
|
|
|
|
tail = head_query.next_union_all;
|
|
|
|
|
|
2016-09-23 20:33:06 +00:00
|
|
|
|
interpreter->next_select_in_union_all = std::make_unique<InterpreterSelectQuery>(head, context, to_stage, subquery_depth);
|
2015-02-13 11:40:58 +00:00
|
|
|
|
interpreter = interpreter->next_select_in_union_all.get();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (is_first_select_inside_union_all && hasAsterisk())
|
2014-12-24 12:59:02 +00:00
|
|
|
|
{
|
2015-07-15 01:26:35 +00:00
|
|
|
|
basicInit(input);
|
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();
|
|
|
|
|
|
2015-07-15 01:26:35 +00:00
|
|
|
|
if (!required_column_names.empty() && (table_column_names.size() != required_column_names.size()))
|
2014-12-24 14:05:55 +00:00
|
|
|
|
{
|
|
|
|
|
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
|
|
|
|
|
2015-07-15 01:26:35 +00:00
|
|
|
|
basicInit(input);
|
2014-12-24 12:59:02 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
2015-07-15 01:26:35 +00:00
|
|
|
|
void InterpreterSelectQuery::basicInit(BlockInputStreamPtr input_)
|
2014-12-24 12:59:02 +00:00
|
|
|
|
{
|
2016-07-22 20:39:28 +00:00
|
|
|
|
auto query_table = query.table();
|
|
|
|
|
|
|
|
|
|
if (query_table && typeid_cast<ASTSelectQuery *>(query_table.get()))
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
|
|
|
|
if (table_column_names.empty())
|
2015-07-15 02:52:19 +00:00
|
|
|
|
{
|
2016-07-22 20:39:28 +00:00
|
|
|
|
table_column_names = InterpreterSelectQuery::getSampleBlock(query_table, context).getColumnsList();
|
2015-07-15 02:52:19 +00:00
|
|
|
|
}
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
2016-07-22 20:39:28 +00:00
|
|
|
|
if (query_table && typeid_cast<const ASTFunction *>(query_table.get()))
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
|
|
|
|
/// Получить табличную функцию
|
2016-07-22 20:39:28 +00:00
|
|
|
|
TableFunctionPtr table_function_ptr = context.getTableFunctionFactory().get(typeid_cast<const ASTFunction *>(query_table.get())->name, context);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
/// Выполнить ее и запомнить результат
|
2016-07-22 20:39:28 +00:00
|
|
|
|
storage = table_function_ptr->execute(query_table, context);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
String database_name;
|
|
|
|
|
String table_name;
|
|
|
|
|
|
|
|
|
|
getDatabaseAndTableNames(database_name, table_name);
|
|
|
|
|
|
|
|
|
|
storage = context.getTable(database_name, table_name);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
table_lock = storage->lockStructure(false);
|
|
|
|
|
if (table_column_names.empty())
|
2015-07-15 01:26:35 +00:00
|
|
|
|
table_column_names = storage->getColumnsListNonMaterialized();
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-07-15 01:26:35 +00:00
|
|
|
|
if (table_column_names.empty())
|
2014-12-19 12:48:09 +00:00
|
|
|
|
throw Exception("There are no available columns", ErrorCodes::THERE_IS_NO_COLUMN);
|
|
|
|
|
|
2016-09-23 20:33:06 +00:00
|
|
|
|
query_analyzer = std::make_unique<ExpressionAnalyzer>(query_ptr, context, storage, table_column_names, subquery_depth, !only_analyze);
|
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-07-15 02:52:19 +00:00
|
|
|
|
query_analyzer.reset(
|
|
|
|
|
new ExpressionAnalyzer(query_ptr, context, storage, table_column_names, subquery_depth, !only_analyze));
|
2015-07-15 01:26:35 +00:00
|
|
|
|
|
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-07-15 02:52:19 +00:00
|
|
|
|
p->query_analyzer.reset(
|
|
|
|
|
new ExpressionAnalyzer(p->query_ptr, p->context, p->storage, p->table_column_names, p->subquery_depth, !only_analyze));
|
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_,
|
2015-07-13 15:02:29 +00:00
|
|
|
|
size_t subquery_depth_, BlockInputStreamPtr input_)
|
2015-07-15 02:52:19 +00:00
|
|
|
|
: query_ptr(query_ptr_), query(typeid_cast<ASTSelectQuery &>(*query_ptr)),
|
|
|
|
|
context(context_), to_stage(to_stage_), subquery_depth(subquery_depth_),
|
|
|
|
|
is_first_select_inside_union_all(query.isUnionAllHead()),
|
|
|
|
|
log(&Logger::get("InterpreterSelectQuery"))
|
2015-07-13 15:02:29 +00:00
|
|
|
|
{
|
2015-07-15 02:52:19 +00:00
|
|
|
|
init(input_);
|
2015-07-13 15:02:29 +00:00
|
|
|
|
}
|
|
|
|
|
|
2015-07-15 02:52:19 +00:00
|
|
|
|
InterpreterSelectQuery::InterpreterSelectQuery(OnlyAnalyzeTag, ASTPtr query_ptr_, const Context & context_)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
: query_ptr(query_ptr_), query(typeid_cast<ASTSelectQuery &>(*query_ptr)),
|
2015-07-15 02:52:19 +00:00
|
|
|
|
context(context_), to_stage(QueryProcessingStage::Complete), subquery_depth(0),
|
|
|
|
|
is_first_select_inside_union_all(false), only_analyze(true),
|
2014-12-19 12:48:09 +00:00
|
|
|
|
log(&Logger::get("InterpreterSelectQuery"))
|
2013-11-08 17:43:03 +00:00
|
|
|
|
{
|
2015-07-15 02:52:19 +00:00
|
|
|
|
init({});
|
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_)
|
2015-07-15 02:52:19 +00:00
|
|
|
|
: InterpreterSelectQuery(query_ptr_, context_, required_column_names_, {}, to_stage_, subquery_depth_, input_)
|
2013-11-08 17:43:03 +00:00
|
|
|
|
{
|
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_,
|
2015-07-15 01:26:35 +00:00
|
|
|
|
const NamesAndTypesList & table_column_names_, QueryProcessingStage::Enum to_stage_, size_t subquery_depth_, BlockInputStreamPtr input_)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
: query_ptr(query_ptr_), query(typeid_cast<ASTSelectQuery &>(*query_ptr)),
|
2015-07-15 01:26:35 +00:00
|
|
|
|
context(context_), to_stage(to_stage_), subquery_depth(subquery_depth_), table_column_names(table_column_names_),
|
2015-07-10 18:26:46 +00:00
|
|
|
|
is_first_select_inside_union_all(query.isUnionAllHead()),
|
2014-12-19 12:48:09 +00:00
|
|
|
|
log(&Logger::get("InterpreterSelectQuery"))
|
2015-01-03 03:18:49 +00:00
|
|
|
|
{
|
2015-07-15 01:26:35 +00:00
|
|
|
|
init(input_, required_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)
|
2015-07-10 18:26:46 +00:00
|
|
|
|
{
|
2015-02-13 11:40:58 +00:00
|
|
|
|
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-07-10 18:26:46 +00:00
|
|
|
|
}
|
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)
|
2015-07-10 18:26:46 +00:00
|
|
|
|
{
|
2015-02-13 11:40:58 +00:00
|
|
|
|
for (auto p = next_select_in_union_all.get(); p != nullptr; p = p->next_select_in_union_all.get())
|
|
|
|
|
p->query.renameColumns(query);
|
2015-07-10 18:26:46 +00:00
|
|
|
|
}
|
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)
|
2015-07-10 18:26:46 +00:00
|
|
|
|
{
|
2015-02-13 11:40:58 +00:00
|
|
|
|
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-07-10 18:26:46 +00:00
|
|
|
|
}
|
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)
|
2015-07-10 18:26:46 +00:00
|
|
|
|
{
|
2015-02-13 11:40:58 +00:00
|
|
|
|
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);
|
2015-07-10 18:26:46 +00:00
|
|
|
|
}
|
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
|
|
|
|
{
|
2016-07-22 20:39:28 +00:00
|
|
|
|
auto query_database = query.database();
|
|
|
|
|
auto query_table = query.table();
|
|
|
|
|
|
2014-12-19 12:48:09 +00:00
|
|
|
|
/** Если таблица не указана - используем таблицу system.one.
|
|
|
|
|
* Если база данных не указана - используем текущую базу данных.
|
|
|
|
|
*/
|
2016-07-22 20:39:28 +00:00
|
|
|
|
if (query_database)
|
|
|
|
|
database_name = typeid_cast<ASTIdentifier &>(*query_database).name;
|
|
|
|
|
if (query_table)
|
|
|
|
|
table_name = typeid_cast<ASTIdentifier &>(*query_table).name;
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
2016-07-22 20:39:28 +00:00
|
|
|
|
if (!query_table)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
|
|
|
|
database_name = "system";
|
|
|
|
|
table_name = "one";
|
|
|
|
|
}
|
2016-07-22 20:39:28 +00:00
|
|
|
|
else if (!query_database)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
|
|
|
|
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)
|
|
|
|
|
{
|
2015-07-17 01:27:35 +00:00
|
|
|
|
ColumnWithTypeAndName & col = block.getByPosition(i);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
col.column = col.type->createColumn();
|
|
|
|
|
}
|
|
|
|
|
return block;
|
2011-10-30 05:19:41 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2015-07-15 02:58:28 +00:00
|
|
|
|
Block InterpreterSelectQuery::getSampleBlock(ASTPtr query_ptr_, const Context & context_)
|
2015-07-13 15:02:29 +00:00
|
|
|
|
{
|
2015-07-15 02:52:19 +00:00
|
|
|
|
return InterpreterSelectQuery(OnlyAnalyzeTag(), query_ptr_, context_).getSampleBlock();
|
2015-07-13 15:02:29 +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
|
|
|
|
|
2015-07-22 01:46:35 +00:00
|
|
|
|
if (hasNoData())
|
2015-06-18 02:11:05 +00:00
|
|
|
|
{
|
|
|
|
|
BlockIO res;
|
2016-05-28 12:22:22 +00:00
|
|
|
|
res.in = std::make_shared<NullBlockInputStream>();
|
2015-06-18 02:11:05 +00:00
|
|
|
|
res.in_sample = getSampleBlock();
|
|
|
|
|
return res;
|
|
|
|
|
}
|
2015-01-03 03:18:49 +00:00
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeUnion();
|
2015-01-03 03:18:49 +00:00
|
|
|
|
|
2014-12-19 12:48:09 +00:00
|
|
|
|
/// Ограничения на результат, квота на результат, а также колбек для прогресса.
|
2015-09-04 19:40:55 +00:00
|
|
|
|
if (IProfilingBlockInputStream * stream = dynamic_cast<IProfilingBlockInputStream *>(streams[0].get()))
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
|
|
|
|
/// Ограничения действуют только на конечный результат.
|
|
|
|
|
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
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
transformStreams([&](auto & stream)
|
|
|
|
|
{
|
2016-05-28 12:22:22 +00:00
|
|
|
|
stream = std::make_shared<MaterializingBlockInputStream>(stream);
|
2015-07-22 00:59:22 +00:00
|
|
|
|
});
|
2014-12-19 15:56:12 +00:00
|
|
|
|
}
|
|
|
|
|
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. */
|
2015-07-22 00:59:22 +00:00
|
|
|
|
QueryProcessingStage::Enum from_stage = executeFetchColumns();
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
|
|
|
|
LOG_TRACE(log, QueryProcessingStage::toString(from_stage) << " -> " << QueryProcessingStage::toString(to_stage));
|
|
|
|
|
|
|
|
|
|
if (to_stage > QueryProcessingStage::FetchColumns)
|
|
|
|
|
{
|
2015-07-22 19:43:09 +00:00
|
|
|
|
bool has_join = false;
|
2014-12-19 12:48:09 +00:00
|
|
|
|
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
|
|
|
|
|
2015-08-03 20:11:57 +00:00
|
|
|
|
ExpressionActionsPtr before_join; /// включая JOIN
|
2014-12-19 12:48:09 +00:00
|
|
|
|
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);
|
|
|
|
|
|
2015-07-22 19:43:09 +00:00
|
|
|
|
if (query_analyzer->appendJoin(chain, !first_stage))
|
2015-07-22 01:46:35 +00:00
|
|
|
|
{
|
2015-07-22 19:43:09 +00:00
|
|
|
|
has_join = true;
|
|
|
|
|
before_join = chain.getLastActions();
|
|
|
|
|
chain.addStep();
|
|
|
|
|
|
2016-07-22 20:39:28 +00:00
|
|
|
|
const ASTTableJoin & join = static_cast<const ASTTableJoin &>(*query.join()->table_join);
|
|
|
|
|
if (join.kind == ASTTableJoin::Kind::Full || join.kind == ASTTableJoin::Kind::Right)
|
2015-07-22 19:43:09 +00:00
|
|
|
|
stream_with_non_joined_data = before_join->createStreamWithNonJoinedDataIfFullOrRightJoin(settings.max_block_size);
|
2015-07-22 01:46:35 +00:00
|
|
|
|
}
|
|
|
|
|
|
2014-12-19 12:48:09 +00:00
|
|
|
|
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),
|
|
|
|
|
* чтобы запрос был проанализирован, и в нём могли бы быть обнаружены ошибки (например, несоответствия типов).
|
|
|
|
|
* Иначе мог бы вернуться пустой результат на некорректный запрос.
|
|
|
|
|
*/
|
2015-07-22 01:46:35 +00:00
|
|
|
|
if (hasNoData())
|
2014-12-19 12:48:09 +00:00
|
|
|
|
return;
|
|
|
|
|
|
2016-01-24 06:38:10 +00:00
|
|
|
|
/// Перед выполнением WHERE и HAVING уберем из блока лишние столбцы (в основном, ключи агрегации).
|
|
|
|
|
if (has_where)
|
|
|
|
|
before_where->prependProjectInput();
|
2014-12-19 12:48:09 +00:00
|
|
|
|
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)
|
|
|
|
|
{
|
2015-07-22 19:43:09 +00:00
|
|
|
|
if (has_join)
|
|
|
|
|
for (auto & stream : streams) /// Применяем ко всем источникам кроме stream_with_non_joined_data.
|
2016-05-28 12:22:22 +00:00
|
|
|
|
stream = std::make_shared<ExpressionBlockInputStream>(stream, before_join);
|
2015-07-22 19:43:09 +00:00
|
|
|
|
|
2014-12-19 12:48:09 +00:00
|
|
|
|
if (has_where)
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeWhere(before_where);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
|
|
|
|
if (need_aggregate)
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeAggregation(before_aggregation, aggregate_overflow_row, aggregate_final);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
else
|
|
|
|
|
{
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeExpression(before_order_and_select);
|
|
|
|
|
executeDistinct(true, selected_columns);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
|
|
|
|
|
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)
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeOrder();
|
2015-01-18 08:27:28 +00:00
|
|
|
|
|
2015-07-20 21:43:53 +00:00
|
|
|
|
if (has_order_by && query.limit_length)
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeDistinct(false, selected_columns);
|
2015-07-20 21:43:53 +00:00
|
|
|
|
|
2015-01-18 08:27:28 +00:00
|
|
|
|
if (query.limit_length)
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executePreLimit();
|
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)
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeMergeAggregated(aggregate_overflow_row, aggregate_final);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
|
|
|
|
if (!aggregate_final)
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeTotalsAndHaving(has_having, before_having, aggregate_overflow_row);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
else if (has_having)
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeHaving(before_having);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeExpression(before_order_and_select);
|
|
|
|
|
executeDistinct(true, selected_columns);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
2015-07-22 02:59:47 +00:00
|
|
|
|
need_second_distinct_pass = query.distinct && hasMoreThanOneStream();
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
|
|
|
|
else if (query.group_by_with_totals && !aggregate_final)
|
|
|
|
|
{
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeTotalsAndHaving(false, nullptr, aggregate_overflow_row);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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))
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeMergeSorted();
|
2015-01-18 08:27:28 +00:00
|
|
|
|
else /// Иначе просто сортировка.
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeOrder();
|
2015-01-18 08:27:28 +00:00
|
|
|
|
}
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeProjection(final_projection);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
|
|
|
|
/// На этой стадии можно считать минимумы и максимумы, если надо.
|
|
|
|
|
if (settings.extremes)
|
2015-07-22 00:59:22 +00:00
|
|
|
|
{
|
|
|
|
|
transformStreams([&](auto & stream)
|
|
|
|
|
{
|
2015-09-04 19:40:55 +00:00
|
|
|
|
if (IProfilingBlockInputStream * p_stream = dynamic_cast<IProfilingBlockInputStream *>(stream.get()))
|
2015-01-13 00:36:26 +00:00
|
|
|
|
p_stream->enableExtremes();
|
2015-07-22 00:59:22 +00:00
|
|
|
|
});
|
|
|
|
|
}
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
|
|
|
|
/** Оптимизация - если источников несколько и есть LIMIT, то сначала применим предварительный LIMIT,
|
|
|
|
|
* ограничивающий число записей в каждом до offset + limit.
|
|
|
|
|
*/
|
2015-07-22 02:59:47 +00:00
|
|
|
|
if (query.limit_length && hasMoreThanOneStream() && !query.distinct)
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executePreLimit();
|
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-07-22 02:59:47 +00:00
|
|
|
|
if (union_within_single_query || stream_with_non_joined_data)
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeUnion();
|
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)
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeDistinct(false, Names());
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeLimit();
|
2015-04-21 15:12:08 +00:00
|
|
|
|
}
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Если данных нет. */
|
2015-07-22 01:46:35 +00:00
|
|
|
|
if (hasNoData())
|
2014-12-19 12:48:09 +00:00
|
|
|
|
return;
|
|
|
|
|
|
|
|
|
|
SubqueriesForSets subqueries_for_sets = query_analyzer->getSubqueriesForSets();
|
|
|
|
|
if (!subqueries_for_sets.empty())
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeSubqueriesInSetsAndJoins(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
|
|
|
|
}
|
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
QueryProcessingStage::Enum InterpreterSelectQuery::executeFetchColumns()
|
2012-05-09 13:12:38 +00:00
|
|
|
|
{
|
2015-07-22 01:46:35 +00:00
|
|
|
|
if (!hasNoData())
|
2014-12-19 12:48:09 +00:00
|
|
|
|
return QueryProcessingStage::FetchColumns;
|
|
|
|
|
|
|
|
|
|
/// Интерпретатор подзапроса, если подзапрос
|
2016-05-28 12:22:22 +00:00
|
|
|
|
std::experimental::optional<InterpreterSelectQuery> interpreter_subquery;
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
|
|
|
|
/// Список столбцов, которых нужно прочитать, чтобы выполнить запрос.
|
|
|
|
|
Names required_columns = query_analyzer->getRequiredColumns();
|
2015-10-29 15:14:19 +00:00
|
|
|
|
/// Действия для вычисления ALIAS, если потребуется.
|
|
|
|
|
ExpressionActionsPtr alias_actions;
|
|
|
|
|
/// Требуются ли ALIAS столбцы для выполнения запроса?
|
|
|
|
|
auto alias_columns_required = false;
|
|
|
|
|
|
|
|
|
|
if (storage && !storage->alias_columns.empty())
|
|
|
|
|
{
|
|
|
|
|
for (const auto & column : required_columns)
|
|
|
|
|
{
|
|
|
|
|
const auto default_it = storage->column_defaults.find(column);
|
|
|
|
|
if (default_it != std::end(storage->column_defaults) && default_it->second.type == ColumnDefaultType::Alias)
|
|
|
|
|
{
|
|
|
|
|
alias_columns_required = true;
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (alias_columns_required)
|
|
|
|
|
{
|
|
|
|
|
/// Составим выражение для возврата всех запрошенных столбцов, с вычислением требуемых ALIAS столбцов.
|
2016-05-28 15:42:22 +00:00
|
|
|
|
auto required_columns_expr_list = std::make_shared<ASTExpressionList>();
|
2015-10-29 15:14:19 +00:00
|
|
|
|
|
|
|
|
|
for (const auto & column : required_columns)
|
2015-12-15 14:13:30 +00:00
|
|
|
|
{
|
|
|
|
|
const auto default_it = storage->column_defaults.find(column);
|
|
|
|
|
if (default_it != std::end(storage->column_defaults) && default_it->second.type == ColumnDefaultType::Alias)
|
|
|
|
|
required_columns_expr_list->children.emplace_back(setAlias(default_it->second.expression->clone(), column));
|
|
|
|
|
else
|
2016-05-28 15:56:51 +00:00
|
|
|
|
required_columns_expr_list->children.emplace_back(std::make_shared<ASTIdentifier>(StringRange(), column));
|
2015-12-15 14:13:30 +00:00
|
|
|
|
}
|
2015-10-29 15:14:19 +00:00
|
|
|
|
|
|
|
|
|
alias_actions = ExpressionAnalyzer{required_columns_expr_list, context, storage, table_column_names}.getActions(true);
|
|
|
|
|
|
|
|
|
|
/// Множество требуемых столбцов могло быть дополнено в результате добавления действия для вычисления ALIAS.
|
|
|
|
|
required_columns = alias_actions->getRequiredColumns();
|
|
|
|
|
}
|
|
|
|
|
}
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
2016-07-22 20:39:28 +00:00
|
|
|
|
auto query_table = query.table();
|
|
|
|
|
if (query_table && typeid_cast<ASTSelectQuery *>(query_table.get()))
|
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);
|
|
|
|
|
|
2016-05-28 12:22:22 +00:00
|
|
|
|
interpreter_subquery.emplace(
|
2016-07-22 20:39:28 +00:00
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
2016-07-22 20:39:28 +00:00
|
|
|
|
if (query.sample_size() && (!storage || !storage->supportsSampling()))
|
2014-12-19 12:48:09 +00:00
|
|
|
|
throw Exception("Illegal SAMPLE: table doesn't support sampling", ErrorCodes::SAMPLING_NOT_SUPPORTED);
|
|
|
|
|
|
2016-07-22 20:39:28 +00:00
|
|
|
|
if (query.final() && (!storage || !storage->supportsFinal()))
|
2014-12-19 12:48:09 +00:00
|
|
|
|
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;
|
|
|
|
|
|
2016-06-30 20:39:35 +00:00
|
|
|
|
if (max_streams == 0)
|
|
|
|
|
throw Exception("Logical error: zero number of streams requested", ErrorCodes::LOGICAL_ERROR);
|
|
|
|
|
|
2015-05-11 00:11:22 +00:00
|
|
|
|
/// Если надо - запрашиваем больше источников, чем количество потоков - для более равномерного распределения работы по потокам.
|
|
|
|
|
if (max_streams > 1 && !is_remote)
|
|
|
|
|
max_streams *= settings.max_streams_to_max_threads_ratio;
|
|
|
|
|
|
2015-07-10 18:26:46 +00:00
|
|
|
|
ASTPtr actual_query_ptr;
|
|
|
|
|
if (storage->isRemote())
|
|
|
|
|
{
|
|
|
|
|
/// В случае удаленного запроса отправляем только SELECT, который выполнится.
|
2015-07-11 15:16:59 +00:00
|
|
|
|
actual_query_ptr = query.cloneFirstSelect();
|
2015-07-10 18:26:46 +00:00
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
actual_query_ptr = query_ptr;
|
|
|
|
|
|
|
|
|
|
streams = storage->read(required_columns, actual_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
|
|
|
|
|
2015-10-29 15:14:19 +00:00
|
|
|
|
if (alias_actions)
|
|
|
|
|
/// Обернем каждый поток, возвращенный из таблицы, с целью вычисления и добавления ALIAS столбцов
|
|
|
|
|
transformStreams([&] (auto & stream)
|
|
|
|
|
{
|
2016-05-28 12:22:22 +00:00
|
|
|
|
stream = std::make_shared<ExpressionBlockInputStream>(stream, alias_actions);
|
2015-10-29 15:14:19 +00:00
|
|
|
|
});
|
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
transformStreams([&](auto & stream)
|
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
stream->addTableLock(table_lock);
|
2015-07-22 00:59:22 +00:00
|
|
|
|
});
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
|
|
|
|
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-07-22 00:59:22 +00:00
|
|
|
|
transformStreams([&](auto & stream)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2015-09-04 19:40:55 +00:00
|
|
|
|
if (IProfilingBlockInputStream * p_stream = dynamic_cast<IProfilingBlockInputStream *>(stream.get()))
|
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
|
|
|
|
}
|
2015-07-22 00:59:22 +00:00
|
|
|
|
});
|
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
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
void InterpreterSelectQuery::executeWhere(ExpressionActionsPtr expression)
|
2012-08-27 05:13:14 +00:00
|
|
|
|
{
|
2015-07-22 00:59:22 +00:00
|
|
|
|
transformStreams([&](auto & stream)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2016-05-28 12:22:22 +00:00
|
|
|
|
stream = std::make_shared<FilterBlockInputStream>(stream, expression, query.where_expression->getColumnName());
|
2015-07-22 00:59:22 +00:00
|
|
|
|
});
|
2012-08-27 05:13:14 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
void InterpreterSelectQuery::executeAggregation(ExpressionActionsPtr expression, bool overflow_row, bool final)
|
2012-05-09 13:12:38 +00:00
|
|
|
|
{
|
2015-07-22 00:59:22 +00:00
|
|
|
|
transformStreams([&](auto & stream)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2016-05-28 12:22:22 +00:00
|
|
|
|
stream = std::make_shared<ExpressionBlockInputStream>(stream, expression);
|
2015-07-22 00:59:22 +00:00
|
|
|
|
});
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
|
|
|
|
Names key_names;
|
|
|
|
|
AggregateDescriptions aggregates;
|
|
|
|
|
query_analyzer->getAggregateInfo(key_names, aggregates);
|
|
|
|
|
|
2015-12-01 14:43:51 +00:00
|
|
|
|
/** Двухуровневая агрегация полезна в двух случаях:
|
|
|
|
|
* 1. Делается параллельная агрегация, и результаты надо параллельно мерджить.
|
|
|
|
|
* 2. Делается агрегация с сохранением временных данных на диск, и их нужно мерджить эффективно по памяти.
|
|
|
|
|
*/
|
|
|
|
|
bool allow_to_use_two_level_group_by = streams.size() > 1 || settings.limits.max_bytes_before_external_group_by != 0;
|
|
|
|
|
|
2015-11-30 16:57:05 +00:00
|
|
|
|
Aggregator::Params params(key_names, aggregates,
|
|
|
|
|
overflow_row, settings.limits.max_rows_to_group_by, settings.limits.group_by_overflow_mode,
|
|
|
|
|
settings.compile ? &context.getCompiler() : nullptr, settings.min_count_to_compile,
|
2015-12-01 14:43:51 +00:00
|
|
|
|
allow_to_use_two_level_group_by ? settings.group_by_two_level_threshold : SettingUInt64(0),
|
|
|
|
|
allow_to_use_two_level_group_by ? settings.group_by_two_level_threshold_bytes : SettingUInt64(0),
|
2015-11-30 19:57:46 +00:00
|
|
|
|
settings.limits.max_bytes_before_external_group_by, context.getTemporaryPath());
|
2015-11-30 16:57:05 +00:00
|
|
|
|
|
2014-12-19 12:48:09 +00:00
|
|
|
|
/// Если источников несколько, то выполняем параллельную агрегацию
|
|
|
|
|
if (streams.size() > 1)
|
|
|
|
|
{
|
2016-05-28 12:22:22 +00:00
|
|
|
|
streams[0] = std::make_shared<ParallelAggregatingBlockInputStream>(
|
2015-12-03 05:03:23 +00:00
|
|
|
|
streams, stream_with_non_joined_data, params, final,
|
|
|
|
|
settings.max_threads,
|
|
|
|
|
settings.aggregation_memory_efficient_merge_threads
|
|
|
|
|
? settings.aggregation_memory_efficient_merge_threads
|
|
|
|
|
: settings.max_threads);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
2015-07-22 02:59:47 +00:00
|
|
|
|
stream_with_non_joined_data = nullptr;
|
2014-12-19 12:48:09 +00:00
|
|
|
|
streams.resize(1);
|
|
|
|
|
}
|
|
|
|
|
else
|
2015-07-22 01:46:35 +00:00
|
|
|
|
{
|
|
|
|
|
BlockInputStreams inputs;
|
|
|
|
|
if (!streams.empty())
|
|
|
|
|
inputs.push_back(streams[0]);
|
|
|
|
|
else
|
|
|
|
|
streams.resize(1);
|
|
|
|
|
|
|
|
|
|
if (stream_with_non_joined_data)
|
|
|
|
|
inputs.push_back(stream_with_non_joined_data);
|
|
|
|
|
|
2016-05-28 12:22:22 +00:00
|
|
|
|
streams[0] = std::make_shared<AggregatingBlockInputStream>(std::make_shared<ConcatBlockInputStream>(inputs), params, final);
|
2015-07-22 02:59:47 +00:00
|
|
|
|
|
|
|
|
|
stream_with_non_joined_data = nullptr;
|
2015-07-22 01:46:35 +00:00
|
|
|
|
}
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
2011-11-06 22:00:39 +00:00
|
|
|
|
|
2012-05-09 13:12:38 +00:00
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
void InterpreterSelectQuery::executeMergeAggregated(bool overflow_row, bool final)
|
2012-05-30 01:38:02 +00:00
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
Names key_names;
|
|
|
|
|
AggregateDescriptions aggregates;
|
|
|
|
|
query_analyzer->getAggregateInfo(key_names, aggregates);
|
2015-07-30 23:41:02 +00:00
|
|
|
|
|
|
|
|
|
/** Есть два режима распределённой агрегации.
|
|
|
|
|
*
|
|
|
|
|
* 1. В разных потоках читать из удалённых серверов блоки.
|
|
|
|
|
* Сохранить все блоки в оперативку. Объединить блоки.
|
|
|
|
|
* Если агрегация двухуровневая - распараллелить по номерам корзин.
|
|
|
|
|
*
|
|
|
|
|
* 2. В одном потоке читать по очереди блоки с разных серверов.
|
|
|
|
|
* В оперативке хранится только по одному блоку с каждого сервера.
|
|
|
|
|
* Если агрегация двухуровневая - последовательно объединяем блоки каждого следующего уровня.
|
|
|
|
|
*
|
|
|
|
|
* Второй вариант расходует меньше памяти (до 256 раз меньше)
|
|
|
|
|
* в случае двухуровневой агрегации, которая используется для больших результатов после GROUP BY,
|
|
|
|
|
* но при этом может работать медленнее.
|
|
|
|
|
*/
|
|
|
|
|
|
2015-11-30 16:57:05 +00:00
|
|
|
|
Aggregator::Params params(key_names, aggregates, overflow_row);
|
|
|
|
|
|
2015-07-30 23:41:02 +00:00
|
|
|
|
if (!settings.distributed_aggregation_memory_efficient)
|
|
|
|
|
{
|
|
|
|
|
/// Склеим несколько источников в один, распараллеливая работу.
|
|
|
|
|
executeUnion();
|
|
|
|
|
|
|
|
|
|
/// Теперь объединим агрегированные блоки
|
2016-05-28 12:22:22 +00:00
|
|
|
|
streams[0] = std::make_shared<MergingAggregatedBlockInputStream>(streams[0], params, final, original_max_threads);
|
2015-07-30 23:41:02 +00:00
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
2016-05-28 12:22:22 +00:00
|
|
|
|
streams[0] = std::make_shared<MergingAggregatedMemoryEfficientBlockInputStream>(streams, params, final,
|
2015-12-05 04:20:37 +00:00
|
|
|
|
settings.max_threads,
|
2015-12-03 05:03:23 +00:00
|
|
|
|
settings.aggregation_memory_efficient_merge_threads
|
|
|
|
|
? size_t(settings.aggregation_memory_efficient_merge_threads)
|
|
|
|
|
: original_max_threads);
|
|
|
|
|
|
2015-07-30 23:41:02 +00:00
|
|
|
|
streams.resize(1);
|
|
|
|
|
}
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
void InterpreterSelectQuery::executeHaving(ExpressionActionsPtr expression)
|
2012-05-09 13:12:38 +00:00
|
|
|
|
{
|
2015-07-22 00:59:22 +00:00
|
|
|
|
transformStreams([&](auto & stream)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2016-05-28 12:22:22 +00:00
|
|
|
|
stream = std::make_shared<FilterBlockInputStream>(stream, expression, query.having_expression->getColumnName());
|
2015-07-22 00:59:22 +00:00
|
|
|
|
});
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
|
|
|
|
|
2011-09-25 03:37:09 +00:00
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
void InterpreterSelectQuery::executeTotalsAndHaving(bool has_having, ExpressionActionsPtr expression, bool overflow_row)
|
2014-02-27 12:49:21 +00:00
|
|
|
|
{
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeUnion();
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
2016-05-28 12:22:22 +00:00
|
|
|
|
streams[0] = std::make_shared<TotalsHavingBlockInputStream>(
|
2016-01-13 00:32:59 +00:00
|
|
|
|
streams[0], 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
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
void InterpreterSelectQuery::executeExpression(ExpressionActionsPtr expression)
|
2012-05-09 13:12:38 +00:00
|
|
|
|
{
|
2015-07-22 00:59:22 +00:00
|
|
|
|
transformStreams([&](auto & stream)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2016-05-28 12:22:22 +00:00
|
|
|
|
stream = std::make_shared<ExpressionBlockInputStream>(stream, expression);
|
2015-07-22 00:59:22 +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
|
|
|
|
|
2016-11-20 12:43:20 +00:00
|
|
|
|
std::shared_ptr<Collator> collator;
|
|
|
|
|
if (order_by_elem.collation)
|
|
|
|
|
collator = std::make_shared<Collator>(typeid_cast<const ASTLiteral &>(*order_by_elem.collation).value.get<String>());
|
|
|
|
|
|
|
|
|
|
order_descr.emplace_back(name, order_by_elem.direction, 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;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
void InterpreterSelectQuery::executeOrder()
|
2015-01-18 08:27:28 +00:00
|
|
|
|
{
|
|
|
|
|
SortDescription order_descr = getSortDescription(query);
|
|
|
|
|
size_t limit = getLimitForSorting(query);
|
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
transformStreams([&](auto & stream)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2016-05-28 12:22:22 +00:00
|
|
|
|
auto sorting_stream = std::make_shared<PartialSortingBlockInputStream>(stream, order_descr, limit);
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
|
|
|
|
/// Ограничения на сортировку
|
|
|
|
|
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;
|
2015-07-22 00:59:22 +00:00
|
|
|
|
});
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
|
|
|
|
/// Если потоков несколько, то объединяем их в один
|
2015-07-22 00:59:22 +00:00
|
|
|
|
executeUnion();
|
2014-12-19 12:48:09 +00:00
|
|
|
|
|
2015-01-07 17:19:23 +00:00
|
|
|
|
/// Сливаем сортированные блоки.
|
2016-05-28 12:22:22 +00:00
|
|
|
|
streams[0] = std::make_shared<MergeSortingBlockInputStream>(
|
2015-07-22 01:46:35 +00:00
|
|
|
|
streams[0], 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-07-22 00:59:22 +00:00
|
|
|
|
void InterpreterSelectQuery::executeMergeSorted()
|
2015-01-18 08:27:28 +00:00
|
|
|
|
{
|
|
|
|
|
SortDescription order_descr = getSortDescription(query);
|
|
|
|
|
size_t limit = getLimitForSorting(query);
|
|
|
|
|
|
|
|
|
|
/// Если потоков несколько, то объединяем их в один
|
2015-07-22 02:59:47 +00:00
|
|
|
|
if (hasMoreThanOneStream())
|
2015-01-18 08:27:28 +00:00
|
|
|
|
{
|
|
|
|
|
/** MergingSortedBlockInputStream читает источники последовательно.
|
|
|
|
|
* Чтобы данные на удалённых серверах готовились параллельно, оборачиваем в AsynchronousBlockInputStream.
|
|
|
|
|
*/
|
2015-07-22 00:59:22 +00:00
|
|
|
|
transformStreams([&](auto & stream)
|
|
|
|
|
{
|
2016-05-28 12:22:22 +00:00
|
|
|
|
stream = std::make_shared<AsynchronousBlockInputStream>(stream);
|
2015-07-22 00:59:22 +00:00
|
|
|
|
});
|
2015-01-18 08:27:28 +00:00
|
|
|
|
|
|
|
|
|
/// Сливаем сортированные источники в один сортированный источник.
|
2016-05-28 12:22:22 +00:00
|
|
|
|
streams[0] = std::make_shared<MergingSortedBlockInputStream>(streams, order_descr, settings.max_block_size, limit);
|
2015-01-18 08:27:28 +00:00
|
|
|
|
streams.resize(1);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
void InterpreterSelectQuery::executeProjection(ExpressionActionsPtr expression)
|
2013-06-03 10:18:41 +00:00
|
|
|
|
{
|
2015-07-22 00:59:22 +00:00
|
|
|
|
transformStreams([&](auto & stream)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2016-05-28 12:22:22 +00:00
|
|
|
|
stream = std::make_shared<ExpressionBlockInputStream>(stream, expression);
|
2015-07-22 00:59:22 +00:00
|
|
|
|
});
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
|
|
|
|
|
2012-02-27 06:28:20 +00:00
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
void InterpreterSelectQuery::executeDistinct(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-07-22 00:59:22 +00:00
|
|
|
|
transformStreams([&](auto & stream)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2016-05-28 12:22:22 +00:00
|
|
|
|
stream = std::make_shared<DistinctBlockInputStream>(stream, settings.limits, limit_for_distinct, columns);
|
2015-07-22 00:59:22 +00:00
|
|
|
|
});
|
2015-04-21 22:28:42 +00:00
|
|
|
|
|
2015-07-22 02:59:47 +00:00
|
|
|
|
if (hasMoreThanOneStream())
|
2015-04-21 22:28:42 +00:00
|
|
|
|
union_within_single_query = true;
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
2013-06-01 07:43:57 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
void InterpreterSelectQuery::executeUnion()
|
2012-05-09 13:12:38 +00:00
|
|
|
|
{
|
2014-12-19 12:48:09 +00:00
|
|
|
|
/// Если до сих пор есть несколько потоков, то объединяем их в один
|
2015-07-22 02:59:47 +00:00
|
|
|
|
if (hasMoreThanOneStream())
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2016-05-28 12:22:22 +00:00
|
|
|
|
streams[0] = std::make_shared<UnionBlockInputStream<>>(streams, stream_with_non_joined_data, settings.max_threads);
|
2015-07-22 02:59:47 +00:00
|
|
|
|
stream_with_non_joined_data = nullptr;
|
2014-12-19 12:48:09 +00:00
|
|
|
|
streams.resize(1);
|
2015-04-21 15:12:08 +00:00
|
|
|
|
union_within_single_query = false;
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
2015-07-22 02:59:47 +00:00
|
|
|
|
else if (stream_with_non_joined_data)
|
|
|
|
|
{
|
|
|
|
|
streams.push_back(stream_with_non_joined_data);
|
|
|
|
|
stream_with_non_joined_data = nullptr;
|
|
|
|
|
union_within_single_query = false;
|
|
|
|
|
}
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2012-06-24 23:17:06 +00:00
|
|
|
|
/// Предварительный LIMIT - применяется в каждом источнике, если источников несколько, до их объединения.
|
2015-07-22 00:59:22 +00:00
|
|
|
|
void InterpreterSelectQuery::executePreLimit()
|
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-07-22 00:59:22 +00:00
|
|
|
|
transformStreams([&](auto & stream)
|
2014-12-19 12:48:09 +00:00
|
|
|
|
{
|
2016-05-28 12:22:22 +00:00
|
|
|
|
stream = std::make_shared<LimitBlockInputStream>(stream, limit_length + limit_offset, 0);
|
2015-07-22 00:59:22 +00:00
|
|
|
|
});
|
2015-04-21 22:28:42 +00:00
|
|
|
|
|
2015-07-22 02:59:47 +00:00
|
|
|
|
if (hasMoreThanOneStream())
|
2015-04-21 15:12:08 +00:00
|
|
|
|
union_within_single_query = true;
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
2012-06-24 23:17:06 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
void InterpreterSelectQuery::executeLimit()
|
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)
|
|
|
|
|
{
|
2015-09-04 19:40:55 +00:00
|
|
|
|
/** Редкий случай:
|
|
|
|
|
* если нет WITH TOTALS и есть подзапрос в FROM, и там на одном из уровней есть WITH TOTALS,
|
|
|
|
|
* то при использовании LIMIT-а следует читать данные до конца, а не отменять выполнение запроса раньше,
|
|
|
|
|
* потому что при отмене выполнения запроса, мы не получим данные для totals с удалённого сервера.
|
2015-12-04 20:33:38 +00:00
|
|
|
|
*
|
|
|
|
|
* Ещё случай:
|
|
|
|
|
* если есть WITH TOTALS и нет ORDER BY, то читать данные до конца,
|
|
|
|
|
* иначе TOTALS посчитается по неполным данным.
|
2015-09-04 19:40:55 +00:00
|
|
|
|
*/
|
|
|
|
|
bool always_read_till_end = false;
|
2015-12-04 20:33:38 +00:00
|
|
|
|
|
|
|
|
|
if (query.group_by_with_totals && !query.order_expression_list)
|
|
|
|
|
{
|
|
|
|
|
always_read_till_end = true;
|
|
|
|
|
}
|
|
|
|
|
|
2016-07-22 20:39:28 +00:00
|
|
|
|
auto query_table = query.table();
|
|
|
|
|
if (!query.group_by_with_totals && query_table && typeid_cast<const ASTSelectQuery *>(query_table.get()))
|
2015-09-04 19:40:55 +00:00
|
|
|
|
{
|
2016-07-22 20:39:28 +00:00
|
|
|
|
const ASTSelectQuery * subquery = static_cast<const ASTSelectQuery *>(query_table.get());
|
2015-09-04 19:40:55 +00:00
|
|
|
|
|
2016-07-22 20:39:28 +00:00
|
|
|
|
while (subquery->table())
|
2015-09-04 19:40:55 +00:00
|
|
|
|
{
|
|
|
|
|
if (subquery->group_by_with_totals)
|
|
|
|
|
{
|
|
|
|
|
/** NOTE Можно ещё проверять, что таблица в подзапросе - распределённая, и что она смотрит только на один шард.
|
|
|
|
|
* В остальных случаях totals будет вычислен на сервере-инициаторе запроса, и читать данные до конца не обязательно.
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
always_read_till_end = true;
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
|
2016-07-22 20:39:28 +00:00
|
|
|
|
auto subquery_table = subquery->table();
|
|
|
|
|
if (typeid_cast<const ASTSelectQuery *>(subquery_table.get()))
|
|
|
|
|
subquery = static_cast<const ASTSelectQuery *>(subquery_table.get());
|
2015-09-04 19:40:55 +00:00
|
|
|
|
else
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2015-07-22 01:46:35 +00:00
|
|
|
|
transformStreams([&](auto & stream)
|
|
|
|
|
{
|
2016-05-28 12:22:22 +00:00
|
|
|
|
stream = std::make_shared<LimitBlockInputStream>(stream, limit_length, limit_offset, always_read_till_end);
|
2015-07-22 01:46:35 +00:00
|
|
|
|
});
|
2014-12-19 12:48:09 +00:00
|
|
|
|
}
|
2011-08-28 05:13:24 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2015-07-22 00:59:22 +00:00
|
|
|
|
void InterpreterSelectQuery::executeSubqueriesInSetsAndJoins(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-07-22 00:59:22 +00:00
|
|
|
|
executeUnion();
|
2016-05-28 12:22:22 +00:00
|
|
|
|
streams[0] = std::make_shared<CreatingSetsBlockInputStream>(streams[0], subqueries_for_sets, settings.limits);
|
2014-03-04 11:26:55 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-11-12 17:55:40 +00:00
|
|
|
|
template <typename Transform>
|
|
|
|
|
void InterpreterSelectQuery::transformStreams(Transform && transform)
|
|
|
|
|
{
|
|
|
|
|
for (auto & stream : streams)
|
|
|
|
|
transform(stream);
|
|
|
|
|
|
|
|
|
|
if (stream_with_non_joined_data)
|
|
|
|
|
transform(stream_with_non_joined_data);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
bool InterpreterSelectQuery::hasNoData() const
|
|
|
|
|
{
|
|
|
|
|
return streams.empty() && !stream_with_non_joined_data;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
bool InterpreterSelectQuery::hasMoreThanOneStream() const
|
|
|
|
|
{
|
|
|
|
|
return streams.size() + (stream_with_non_joined_data ? 1 : 0) > 1;
|
|
|
|
|
}
|
|
|
|
|
|
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
|
|
|
|
}
|