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>
|
2011-09-25 03:37:09 +00:00
|
|
|
|
#include <DB/DataStreams/AggregatingBlockInputStream.h>
|
|
|
|
|
#include <DB/DataStreams/FinalizingAggregatedBlockInputStream.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-09-15 10:53:10 +00:00
|
|
|
|
#include <DB/DataStreams/SplittingAggregatingBlockInputStream.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>
|
2012-06-25 02:52:51 +00:00
|
|
|
|
#include <DB/DataStreams/narrowBlockInputStreams.h>
|
2011-10-30 05:19:41 +00:00
|
|
|
|
#include <DB/DataStreams/copyData.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>
|
2013-10-30 13:52:02 +00:00
|
|
|
|
#include <DB/Storages/StorageView.h>
|
2011-08-28 05:13:24 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
namespace DB
|
|
|
|
|
{
|
|
|
|
|
|
|
|
|
|
|
2012-12-25 20:36:35 +00:00
|
|
|
|
InterpreterSelectQuery::InterpreterSelectQuery(ASTPtr query_ptr_, const Context & context_, QueryProcessingStage::Enum to_stage_,
|
|
|
|
|
size_t subquery_depth_)
|
2012-08-02 17:33:31 +00:00
|
|
|
|
: query_ptr(query_ptr_), query(dynamic_cast<ASTSelectQuery &>(*query_ptr)),
|
2012-12-25 20:36:35 +00:00
|
|
|
|
context(context_), settings(context.getSettings()), to_stage(to_stage_), subquery_depth(subquery_depth_),
|
2012-06-25 03:56:45 +00:00
|
|
|
|
log(&Logger::get("InterpreterSelectQuery"))
|
2011-08-28 05:13:24 +00:00
|
|
|
|
{
|
2012-12-25 20:36:35 +00:00
|
|
|
|
if (settings.limits.max_subquery_depth && subquery_depth > settings.limits.max_subquery_depth)
|
2013-06-21 20:34:19 +00:00
|
|
|
|
throw Exception("Too deep subqueries. Maximum: " + toString(settings.limits.max_subquery_depth),
|
2012-12-25 20:36:35 +00:00
|
|
|
|
ErrorCodes::TOO_DEEP_SUBQUERIES);
|
2013-06-03 10:18:41 +00:00
|
|
|
|
|
|
|
|
|
context.setColumns(!query.table || !dynamic_cast<ASTSelectQuery *>(&*query.table)
|
|
|
|
|
? getTable()->getColumnsList()
|
|
|
|
|
: InterpreterSelectQuery(query.table, context).getSampleBlock().getColumnsList());
|
|
|
|
|
|
|
|
|
|
if (context.getColumns().empty())
|
2013-10-21 11:33:25 +00:00
|
|
|
|
throw Exception("There are no available columns", ErrorCodes::THERE_IS_NO_COLUMN);
|
2013-06-03 10:18:41 +00:00
|
|
|
|
|
|
|
|
|
query_analyzer = new ExpressionAnalyzer(query_ptr, context, subquery_depth);
|
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
|
|
|
|
{
|
|
|
|
|
/** Если таблица не указана - используем таблицу system.one.
|
|
|
|
|
* Если база данных не указана - используем текущую базу данных.
|
|
|
|
|
*/
|
|
|
|
|
if (!query.table)
|
|
|
|
|
{
|
|
|
|
|
database_name = "system";
|
|
|
|
|
table_name = "one";
|
|
|
|
|
}
|
|
|
|
|
else if (!query.database)
|
2012-08-02 17:33:31 +00:00
|
|
|
|
database_name = context.getCurrentDatabase();
|
2011-08-28 05:13:24 +00:00
|
|
|
|
|
|
|
|
|
if (query.database)
|
|
|
|
|
database_name = dynamic_cast<ASTIdentifier &>(*query.database).name;
|
|
|
|
|
if (query.table)
|
|
|
|
|
table_name = dynamic_cast<ASTIdentifier &>(*query.table).name;
|
2012-08-20 19:21:04 +00:00
|
|
|
|
}
|
|
|
|
|
|
2011-08-28 05:13:24 +00:00
|
|
|
|
|
2012-08-20 19:21:04 +00:00
|
|
|
|
StoragePtr InterpreterSelectQuery::getTable()
|
|
|
|
|
{
|
|
|
|
|
String database_name;
|
|
|
|
|
String table_name;
|
|
|
|
|
|
|
|
|
|
getDatabaseAndTableNames(database_name, table_name);
|
2012-08-02 17:33:31 +00:00
|
|
|
|
return context.getTable(database_name, table_name);
|
2011-08-28 05:13:24 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2012-08-20 19:21:04 +00:00
|
|
|
|
ASTPtr InterpreterSelectQuery::getCreateQuery()
|
|
|
|
|
{
|
|
|
|
|
String database_name;
|
|
|
|
|
String table_name;
|
|
|
|
|
|
|
|
|
|
getDatabaseAndTableNames(database_name, table_name);
|
|
|
|
|
return context.getCreateQuery(database_name, table_name);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2011-08-28 05:13:24 +00:00
|
|
|
|
DataTypes InterpreterSelectQuery::getReturnTypes()
|
|
|
|
|
{
|
2013-06-03 10:18:41 +00:00
|
|
|
|
DataTypes res;
|
|
|
|
|
NamesAndTypesList columns = query_analyzer->getSelectSampleBlock().getColumnsList();
|
|
|
|
|
for (NamesAndTypesList::iterator it = columns.begin(); it != columns.end(); ++it)
|
|
|
|
|
{
|
|
|
|
|
res.push_back(it->second);
|
|
|
|
|
}
|
|
|
|
|
return res;
|
2011-08-28 05:13:24 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2011-10-30 05:19:41 +00:00
|
|
|
|
Block InterpreterSelectQuery::getSampleBlock()
|
|
|
|
|
{
|
2013-06-18 14:12:10 +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);
|
2013-06-19 13:09:28 +00:00
|
|
|
|
col.column = col.type->createColumn();
|
2013-06-18 14:12:10 +00:00
|
|
|
|
}
|
|
|
|
|
return block;
|
2011-10-30 05:19:41 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2012-03-05 00:09:41 +00:00
|
|
|
|
/// Превращает источник в асинхронный, если это указано.
|
|
|
|
|
static inline BlockInputStreamPtr maybeAsynchronous(BlockInputStreamPtr in, bool is_async)
|
|
|
|
|
{
|
|
|
|
|
return is_async
|
|
|
|
|
? new AsynchronousBlockInputStream(in)
|
|
|
|
|
: in;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2011-08-28 05:13:24 +00:00
|
|
|
|
BlockInputStreamPtr InterpreterSelectQuery::execute()
|
|
|
|
|
{
|
2012-05-09 13:12:38 +00:00
|
|
|
|
/** Потоки данных. При параллельном выполнении запроса, имеем несколько потоков данных.
|
|
|
|
|
* Если нет GROUP BY, то выполним все операции до ORDER BY и LIMIT параллельно, затем
|
|
|
|
|
* если есть ORDER BY, то склеим потоки с помощью UnionBlockInputStream, а затем MergеSortingBlockInputStream,
|
|
|
|
|
* если нет, то склеим с помощью UnionBlockInputStream,
|
|
|
|
|
* затем применим LIMIT.
|
|
|
|
|
* Если есть GROUP BY, то выполним все операции до GROUP BY, включительно, параллельно;
|
|
|
|
|
* параллельный GROUP BY склеит потоки в один,
|
|
|
|
|
* затем выполним остальные операции с одним получившимся потоком.
|
|
|
|
|
*/
|
|
|
|
|
BlockInputStreams streams;
|
|
|
|
|
|
2012-05-22 18:32:45 +00:00
|
|
|
|
/** Вынем данные из Storage. from_stage - до какой стадии запрос был выполнен в Storage. */
|
2013-06-03 10:18:41 +00:00
|
|
|
|
QueryProcessingStage::Enum from_stage = executeFetchColumns(streams);
|
2012-05-09 13:12:38 +00:00
|
|
|
|
|
2012-05-30 04:45:49 +00:00
|
|
|
|
/** Если данных нет. */
|
|
|
|
|
if (streams.empty())
|
|
|
|
|
return new NullBlockInputStream;
|
|
|
|
|
|
2012-06-25 03:56:45 +00:00
|
|
|
|
LOG_TRACE(log, QueryProcessingStage::toString(from_stage) << " -> " << QueryProcessingStage::toString(to_stage));
|
2012-05-30 01:38:02 +00:00
|
|
|
|
|
2012-05-22 18:32:45 +00:00
|
|
|
|
if (to_stage > QueryProcessingStage::FetchColumns)
|
2012-05-09 13:12:38 +00:00
|
|
|
|
{
|
2013-06-03 10:18:41 +00:00
|
|
|
|
bool has_where = false;
|
|
|
|
|
bool need_aggregate = false;
|
|
|
|
|
bool has_having = false;
|
|
|
|
|
bool has_order_by = false;
|
2012-05-22 18:32:45 +00:00
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
ExpressionActionsPtr before_where;
|
|
|
|
|
ExpressionActionsPtr before_aggregation;
|
|
|
|
|
ExpressionActionsPtr before_having;
|
|
|
|
|
ExpressionActionsPtr before_order_and_select;
|
|
|
|
|
ExpressionActionsPtr final_projection;
|
|
|
|
|
|
|
|
|
|
/// Сначала составим цепочку действий и запомним нужные шаги из нее.
|
|
|
|
|
|
|
|
|
|
ExpressionActionsChain chain;
|
|
|
|
|
|
|
|
|
|
need_aggregate = query_analyzer->hasAggregation();
|
|
|
|
|
|
|
|
|
|
if (from_stage < QueryProcessingStage::WithMergeableState
|
|
|
|
|
&& to_stage >= QueryProcessingStage::WithMergeableState)
|
2012-05-22 18:32:45 +00:00
|
|
|
|
{
|
2013-07-26 16:33:05 +00:00
|
|
|
|
query_analyzer->appendArrayJoin(chain);
|
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
if (query_analyzer->appendWhere(chain))
|
|
|
|
|
{
|
|
|
|
|
has_where = true;
|
2013-06-05 12:46:41 +00:00
|
|
|
|
before_where = chain.getLastActions();
|
2013-06-03 10:18:41 +00:00
|
|
|
|
|
|
|
|
|
/// Если кроме WHERE ничего выполнять не нужно, пометим все исходные столбцы как нужные, чтобы finalize их не выбросил.
|
|
|
|
|
if (!need_aggregate && to_stage == QueryProcessingStage::WithMergeableState)
|
|
|
|
|
{
|
|
|
|
|
Names columns = query_analyzer->getRequiredColumns();
|
2013-06-05 12:46:41 +00:00
|
|
|
|
chain.getLastStep().required_output.insert(chain.getLastStep().required_output.end(),
|
2013-06-03 10:18:41 +00:00
|
|
|
|
columns.begin(), columns.end());
|
|
|
|
|
|
|
|
|
|
chain.finalize();
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
chain.addStep();
|
|
|
|
|
}
|
|
|
|
|
}
|
2013-03-27 12:04:48 +00:00
|
|
|
|
|
2012-05-22 18:32:45 +00:00
|
|
|
|
if (need_aggregate)
|
2013-06-03 10:18:41 +00:00
|
|
|
|
{
|
|
|
|
|
query_analyzer->appendGroupBy(chain);
|
|
|
|
|
query_analyzer->appendAggregateFunctionsArguments(chain);
|
2013-06-05 12:46:41 +00:00
|
|
|
|
before_aggregation = chain.getLastActions();
|
2013-06-03 10:18:41 +00:00
|
|
|
|
|
|
|
|
|
chain.finalize();
|
|
|
|
|
|
|
|
|
|
chain.clear();
|
|
|
|
|
}
|
2012-05-22 18:32:45 +00:00
|
|
|
|
}
|
2013-06-03 10:18:41 +00:00
|
|
|
|
|
|
|
|
|
if (from_stage <= QueryProcessingStage::WithMergeableState
|
|
|
|
|
&& to_stage > QueryProcessingStage::WithMergeableState)
|
2013-03-27 12:04:48 +00:00
|
|
|
|
{
|
2013-06-03 10:18:41 +00:00
|
|
|
|
if (need_aggregate && query_analyzer->appendHaving(chain))
|
|
|
|
|
{
|
|
|
|
|
has_having = true;
|
2013-06-05 12:46:41 +00:00
|
|
|
|
before_having = chain.getLastActions();
|
2013-06-03 10:18:41 +00:00
|
|
|
|
chain.addStep();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
query_analyzer->appendSelect(chain);
|
|
|
|
|
has_order_by = query_analyzer->appendOrderBy(chain);
|
2013-06-05 12:46:41 +00:00
|
|
|
|
before_order_and_select = chain.getLastActions();
|
2013-06-03 10:18:41 +00:00
|
|
|
|
chain.addStep();
|
|
|
|
|
|
|
|
|
|
query_analyzer->appendProjectResult(chain);
|
2013-06-05 12:46:41 +00:00
|
|
|
|
final_projection = chain.getLastActions();
|
2013-06-03 10:18:41 +00:00
|
|
|
|
chain.finalize();
|
|
|
|
|
|
2013-06-17 14:57:03 +00:00
|
|
|
|
/// Если предыдущая стадия запроса выполнялась отдельно, нам могли дать лишних столбцов (например, используемых только в секции WHERE).
|
|
|
|
|
/// Уберем их. Они могут существенно мешать, например, при arrayJoin.
|
|
|
|
|
if (from_stage == QueryProcessingStage::WithMergeableState)
|
|
|
|
|
before_order_and_select->prependProjectInput();
|
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
/// Перед выполнением HAVING уберем из блока лишние столбцы (в основном, ключи агрегации).
|
|
|
|
|
if (has_having)
|
|
|
|
|
before_having->prependProjectInput();
|
2013-03-27 12:04:48 +00:00
|
|
|
|
}
|
2013-06-03 10:18:41 +00:00
|
|
|
|
|
|
|
|
|
/// Теперь составим потоки блоков, выполняющие нужные действия.
|
|
|
|
|
|
|
|
|
|
if (from_stage < QueryProcessingStage::WithMergeableState
|
|
|
|
|
&& to_stage >= QueryProcessingStage::WithMergeableState)
|
|
|
|
|
{
|
|
|
|
|
if (has_where)
|
|
|
|
|
executeWhere(streams, before_where);
|
|
|
|
|
|
|
|
|
|
if (need_aggregate)
|
|
|
|
|
executeAggregation(streams, before_aggregation);
|
2013-06-29 20:32:33 +00:00
|
|
|
|
|
|
|
|
|
/** Оптимизация - при распределённой обработке запроса, на удалённом сервере,
|
|
|
|
|
* если не указаны DISTINCT, GROUP, HAVING, ORDER, но указан LIMIT,
|
|
|
|
|
* то выполним предварительный LIMIT на удалёном сервере.
|
|
|
|
|
*/
|
|
|
|
|
if (to_stage == QueryProcessingStage::WithMergeableState
|
|
|
|
|
&& !query.distinct && !need_aggregate && !has_having && !has_order_by
|
|
|
|
|
&& query.limit_length)
|
|
|
|
|
{
|
|
|
|
|
executePreLimit(streams);
|
|
|
|
|
}
|
2013-06-03 10:18:41 +00:00
|
|
|
|
}
|
2013-06-29 20:32:33 +00:00
|
|
|
|
|
2012-05-22 18:32:45 +00:00
|
|
|
|
if (from_stage <= QueryProcessingStage::WithMergeableState
|
|
|
|
|
&& to_stage > QueryProcessingStage::WithMergeableState)
|
2012-05-09 13:12:38 +00:00
|
|
|
|
{
|
|
|
|
|
if (need_aggregate)
|
2012-05-30 01:38:02 +00:00
|
|
|
|
{
|
|
|
|
|
/// Если нужно объединить агрегированные результаты с нескольких серверов
|
|
|
|
|
if (from_stage == QueryProcessingStage::WithMergeableState)
|
2013-06-03 10:18:41 +00:00
|
|
|
|
executeMergeAggregated(streams);
|
|
|
|
|
|
|
|
|
|
executeFinalizeAggregates(streams);
|
2012-05-30 01:38:02 +00:00
|
|
|
|
}
|
2013-06-03 10:18:41 +00:00
|
|
|
|
|
|
|
|
|
if (has_having)
|
|
|
|
|
executeHaving(streams, before_having);
|
|
|
|
|
|
|
|
|
|
executeOuterExpression(streams, before_order_and_select);
|
|
|
|
|
|
|
|
|
|
if (has_order_by)
|
|
|
|
|
executeOrder(streams);
|
|
|
|
|
|
|
|
|
|
executeProjection(streams, final_projection);
|
|
|
|
|
|
2013-06-01 07:43:57 +00:00
|
|
|
|
/// Сначала выполняем DISTINCT во всех источниках.
|
|
|
|
|
executeDistinct(streams, true);
|
|
|
|
|
|
2013-09-07 02:03:13 +00:00
|
|
|
|
/// На этой стадии можно считать минимумы и максимумы, если надо.
|
|
|
|
|
if (settings.extremes)
|
|
|
|
|
for (BlockInputStreams::iterator it = streams.begin(); it != streams.end(); ++it)
|
|
|
|
|
if (IProfilingBlockInputStream * stream = dynamic_cast<IProfilingBlockInputStream *>(&**it))
|
|
|
|
|
stream->enableExtremes();
|
|
|
|
|
|
2012-06-24 23:17:06 +00:00
|
|
|
|
/** Оптимизация - если источников несколько и есть LIMIT, то сначала применим предварительный LIMIT,
|
2013-06-29 20:32:33 +00:00
|
|
|
|
* ограничивающий число записей в каждом до offset + limit.
|
|
|
|
|
*/
|
2012-06-24 23:17:06 +00:00
|
|
|
|
if (query.limit_length && streams.size() > 1)
|
2013-06-03 10:18:41 +00:00
|
|
|
|
executePreLimit(streams);
|
|
|
|
|
|
2013-06-01 07:43:57 +00:00
|
|
|
|
bool need_second_distinct_pass = streams.size() > 1;
|
2013-06-03 10:18:41 +00:00
|
|
|
|
|
|
|
|
|
executeUnion(streams);
|
|
|
|
|
|
2013-06-01 07:43:57 +00:00
|
|
|
|
/// Если было более одного источника - то нужно выполнить DISTINCT ещё раз после их слияния.
|
|
|
|
|
if (need_second_distinct_pass)
|
|
|
|
|
executeDistinct(streams, false);
|
2013-06-03 10:18:41 +00:00
|
|
|
|
|
2013-06-01 07:43:57 +00:00
|
|
|
|
/** NOTE: В некоторых случаях, DISTINCT можно было бы применять раньше
|
2013-06-29 20:32:33 +00:00
|
|
|
|
* - до сортировки и, возможно, на удалённых серверах.
|
|
|
|
|
*/
|
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
executeLimit(streams);
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
executeUnion(streams);
|
2012-12-25 20:36:35 +00:00
|
|
|
|
|
2013-08-28 20:47:22 +00:00
|
|
|
|
/// Ограничения на результат, квота на результат, а также колбек для прогресса.
|
2012-12-25 20:36:35 +00:00
|
|
|
|
if (IProfilingBlockInputStream * stream = dynamic_cast<IProfilingBlockInputStream *>(&*streams[0]))
|
|
|
|
|
{
|
|
|
|
|
IProfilingBlockInputStream::LocalLimits limits;
|
|
|
|
|
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);
|
2013-08-28 20:47:22 +00:00
|
|
|
|
stream->setQuota(context.getQuota(), IProfilingBlockInputStream::QUOTA_RESULT);
|
2013-02-16 14:55:14 +00:00
|
|
|
|
|
|
|
|
|
stream->setProgressCallback(context.getProgressCallback());
|
2012-12-25 20:36:35 +00:00
|
|
|
|
}
|
2013-02-16 14:55:14 +00:00
|
|
|
|
|
2012-05-09 13:12:38 +00:00
|
|
|
|
return streams[0];
|
|
|
|
|
}
|
|
|
|
|
|
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)
|
|
|
|
|
{
|
|
|
|
|
length = 0;
|
|
|
|
|
offset = 0;
|
|
|
|
|
if (query.limit_length)
|
|
|
|
|
{
|
2013-01-05 20:03:19 +00:00
|
|
|
|
length = safeGet<UInt64>(dynamic_cast<ASTLiteral &>(*query.limit_length).value);
|
2012-05-09 13:12:38 +00:00
|
|
|
|
if (query.limit_offset)
|
2013-01-05 20:03:19 +00:00
|
|
|
|
offset = safeGet<UInt64>(dynamic_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
|
|
|
|
{
|
2011-11-06 02:29:13 +00:00
|
|
|
|
/// Таблица, откуда читать данные, если не подзапрос.
|
|
|
|
|
StoragePtr table;
|
|
|
|
|
/// Интерпретатор подзапроса, если подзапрос
|
|
|
|
|
SharedPtr<InterpreterSelectQuery> interpreter_subquery;
|
2011-08-28 05:13:24 +00:00
|
|
|
|
|
2011-11-06 22:00:39 +00:00
|
|
|
|
if (!query.table || !dynamic_cast<ASTSelectQuery *>(&*query.table))
|
2013-10-30 13:52:02 +00:00
|
|
|
|
{
|
2011-11-06 02:29:13 +00:00
|
|
|
|
table = getTable();
|
2013-10-30 13:52:02 +00:00
|
|
|
|
if (table->getName() == "VIEW")
|
|
|
|
|
query.table = dynamic_cast<StorageView *> (table.get())->getInnerQuery();
|
|
|
|
|
}
|
2013-10-31 18:20:52 +00:00
|
|
|
|
else if (dynamic_cast<ASTSelectQuery *>(&*query.table))
|
2012-12-25 20:36:35 +00:00
|
|
|
|
interpreter_subquery = new InterpreterSelectQuery(query.table, context, QueryProcessingStage::Complete, subquery_depth + 1);
|
2012-10-30 20:15:07 +00:00
|
|
|
|
|
2012-12-12 14:25:55 +00:00
|
|
|
|
if (query.sample_size && (!table || !table->supportsSampling()))
|
|
|
|
|
throw Exception("Illegal SAMPLE: table doesn't support sampling", ErrorCodes::SAMPLING_NOT_SUPPORTED);
|
|
|
|
|
|
2013-04-23 11:08:41 +00:00
|
|
|
|
if (query.final && (!table || !table->supportsFinal()))
|
|
|
|
|
throw Exception("Illegal FINAL", ErrorCodes::ILLEGAL_FINAL);
|
|
|
|
|
|
2012-10-30 20:15:07 +00:00
|
|
|
|
/** При распределённой обработке запроса, в потоках почти не делается вычислений,
|
|
|
|
|
* а делается ожидание и получение данных с удалённых серверов.
|
|
|
|
|
* Если у нас 20 удалённых серверов, а max_threads = 8, то было бы не очень хорошо
|
|
|
|
|
* соединяться и опрашивать только по 8 серверов одновременно.
|
|
|
|
|
* Чтобы одновременно опрашивалось больше удалённых серверов,
|
|
|
|
|
* вместо max_threads используется max_distributed_connections.
|
2013-02-02 22:24:21 +00:00
|
|
|
|
*
|
|
|
|
|
* Сохраним изначальное значение max_threads в settings_for_storage
|
|
|
|
|
* - эти настройки будут переданы на удалённые серверы при распределённой обработке запроса,
|
|
|
|
|
* и там должно быть оригинальное значение max_threads, а не увеличенное.
|
2012-10-30 20:15:07 +00:00
|
|
|
|
*/
|
2013-02-02 22:24:21 +00:00
|
|
|
|
Settings settings_for_storage = settings;
|
2012-11-07 19:56:21 +00:00
|
|
|
|
if (table && table->isRemote())
|
2012-10-30 20:15:07 +00:00
|
|
|
|
settings.max_threads = settings.max_distributed_connections;
|
2011-11-06 02:29:13 +00:00
|
|
|
|
|
|
|
|
|
/// Список столбцов, которых нужно прочитать, чтобы выполнить запрос.
|
2013-06-03 10:18:41 +00:00
|
|
|
|
Names required_columns = query_analyzer->getRequiredColumns();
|
2011-08-28 08:02:11 +00:00
|
|
|
|
|
2012-12-25 20:36:35 +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. "
|
2013-06-21 20:34:19 +00:00
|
|
|
|
"Requested: " + toString(required_columns.size())
|
|
|
|
|
+ ", maximum: " + toString(settings.limits.max_columns_to_read),
|
2012-12-25 20:36:35 +00:00
|
|
|
|
ErrorCodes::TOO_MUCH_COLUMNS);
|
|
|
|
|
|
2011-09-04 05:14:52 +00:00
|
|
|
|
size_t limit_length = 0;
|
|
|
|
|
size_t limit_offset = 0;
|
2012-05-09 13:12:38 +00:00
|
|
|
|
getLimitLengthAndOffset(query, limit_length, limit_offset);
|
2011-09-04 05:14:52 +00:00
|
|
|
|
|
2013-06-01 07:43:57 +00:00
|
|
|
|
/** Оптимизация - если не указаны DISTINCT, WHERE, GROUP, HAVING, ORDER, но указан LIMIT, и limit + offset < max_block_size,
|
2012-06-25 07:26:58 +00:00
|
|
|
|
* то в качестве размера блока будем использовать limit + offset (чтобы не читать из таблицы больше, чем запрошено),
|
|
|
|
|
* а также установим количество потоков в 1 и отменим асинхронное выполнение конвейера запроса.
|
2011-09-04 05:14:52 +00:00
|
|
|
|
*/
|
2013-06-01 07:43:57 +00:00
|
|
|
|
if (!query.distinct && !query.where_expression && !query.group_expression_list && !query.having_expression && !query.order_expression_list
|
2013-06-03 10:18:41 +00:00
|
|
|
|
&& query.limit_length && !query_analyzer->hasAggregation() && limit_length + limit_offset < settings.max_block_size)
|
2011-09-04 05:14:52 +00:00
|
|
|
|
{
|
2012-08-02 17:33:31 +00:00
|
|
|
|
settings.max_block_size = limit_length + limit_offset;
|
|
|
|
|
settings.max_threads = 1;
|
|
|
|
|
settings.asynchronous = false;
|
2011-09-04 05:14:52 +00:00
|
|
|
|
}
|
2012-05-22 18:32:45 +00:00
|
|
|
|
|
|
|
|
|
QueryProcessingStage::Enum from_stage = QueryProcessingStage::FetchColumns;
|
2012-05-09 13:12:38 +00:00
|
|
|
|
|
2012-02-27 06:28:20 +00:00
|
|
|
|
/// Инициализируем изначальные потоки данных, на которые накладываются преобразования запроса. Таблица или подзапрос?
|
2011-11-06 22:00:39 +00:00
|
|
|
|
if (!query.table || !dynamic_cast<ASTSelectQuery *>(&*query.table))
|
2013-02-02 22:24:21 +00:00
|
|
|
|
streams = table->read(required_columns, query_ptr, settings_for_storage, from_stage, settings.max_block_size, settings.max_threads);
|
2011-11-06 02:29:13 +00:00
|
|
|
|
else
|
2012-08-02 17:33:31 +00:00
|
|
|
|
streams.push_back(maybeAsynchronous(interpreter_subquery->execute(), settings.asynchronous));
|
2012-02-27 07:54:16 +00:00
|
|
|
|
|
2012-06-25 03:01:37 +00:00
|
|
|
|
/** Если истчоников слишком много, то склеим их в max_threads источников.
|
|
|
|
|
* (Иначе действия в каждом маленьком источнике, а затем объединение состояний, слишком неэффективно.)
|
|
|
|
|
*/
|
2012-08-02 17:33:31 +00:00
|
|
|
|
if (streams.size() > settings.max_threads)
|
|
|
|
|
streams = narrowBlockInputStreams(streams, settings.max_threads);
|
2012-06-25 03:01:37 +00:00
|
|
|
|
|
2013-08-28 20:47:22 +00:00
|
|
|
|
/** Установка ограничений и квоты на чтение данных.
|
2012-12-25 19:28:59 +00:00
|
|
|
|
* Они устанавливаются на самые "глубокие" чтения.
|
|
|
|
|
* То есть, не должны устанавливаться для чтений из удалённых серверов и подзапросов.
|
|
|
|
|
*/
|
|
|
|
|
if (table && !table->isRemote())
|
|
|
|
|
{
|
|
|
|
|
IProfilingBlockInputStream::LocalLimits limits;
|
|
|
|
|
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;
|
2013-08-28 20:47:22 +00:00
|
|
|
|
|
|
|
|
|
QuotaForIntervals & quota = context.getQuota();
|
2012-12-25 19:28:59 +00:00
|
|
|
|
|
|
|
|
|
for (BlockInputStreams::iterator it = streams.begin(); it != streams.end(); ++it)
|
2013-08-28 20:47:22 +00:00
|
|
|
|
{
|
2012-12-25 19:28:59 +00:00
|
|
|
|
if (IProfilingBlockInputStream * stream = dynamic_cast<IProfilingBlockInputStream *>(&**it))
|
2013-08-28 20:47:22 +00:00
|
|
|
|
{
|
2012-12-25 19:28:59 +00:00
|
|
|
|
stream->setLimits(limits);
|
2013-08-28 20:47:22 +00:00
|
|
|
|
stream->setQuota(quota, IProfilingBlockInputStream::QUOTA_READ);
|
|
|
|
|
}
|
|
|
|
|
}
|
2012-12-25 19:28:59 +00:00
|
|
|
|
}
|
|
|
|
|
|
2012-05-22 18:32:45 +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
|
|
|
|
{
|
2013-06-03 10:18:41 +00:00
|
|
|
|
bool is_async = settings.asynchronous && streams.size() <= settings.max_threads;
|
|
|
|
|
for (BlockInputStreams::iterator it = streams.begin(); it != streams.end(); ++it)
|
2012-08-27 05:13:14 +00:00
|
|
|
|
{
|
2013-06-03 10:18:41 +00:00
|
|
|
|
BlockInputStreamPtr & stream = *it;
|
|
|
|
|
stream = maybeAsynchronous(new ExpressionBlockInputStream(stream, expression), is_async);
|
|
|
|
|
stream = maybeAsynchronous(new FilterBlockInputStream(stream, query.where_expression->getColumnName()), is_async);
|
2012-08-27 05:13:14 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
void InterpreterSelectQuery::executeAggregation(BlockInputStreams & streams, ExpressionActionsPtr expression)
|
2012-05-09 13:12:38 +00:00
|
|
|
|
{
|
2012-08-02 17:33:31 +00:00
|
|
|
|
bool is_async = settings.asynchronous && streams.size() <= settings.max_threads;
|
2012-05-09 13:12:38 +00:00
|
|
|
|
for (BlockInputStreams::iterator it = streams.begin(); it != streams.end(); ++it)
|
|
|
|
|
{
|
|
|
|
|
BlockInputStreamPtr & stream = *it;
|
2013-06-03 10:18:41 +00:00
|
|
|
|
stream = maybeAsynchronous(new ExpressionBlockInputStream(stream, expression), is_async);
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
2012-02-27 06:28:20 +00:00
|
|
|
|
|
2012-05-09 13:12:38 +00:00
|
|
|
|
BlockInputStreamPtr & stream = streams[0];
|
2012-02-27 06:28:20 +00:00
|
|
|
|
|
2013-05-27 14:02:55 +00:00
|
|
|
|
Names key_names;
|
|
|
|
|
AggregateDescriptions aggregates;
|
2013-06-03 10:18:41 +00:00
|
|
|
|
query_analyzer->getAggregateInfo(key_names, aggregates);
|
2013-09-01 04:55:41 +00:00
|
|
|
|
|
2013-10-26 03:20:51 +00:00
|
|
|
|
/// TODO: Оптимизация для случая, когда есть LIMIT, но нет HAVING и ORDER BY.
|
|
|
|
|
|
2013-09-01 04:55:41 +00:00
|
|
|
|
bool separate_totals = to_stage > QueryProcessingStage::WithMergeableState;
|
2013-05-27 14:02:55 +00:00
|
|
|
|
|
2012-06-22 15:39:13 +00:00
|
|
|
|
/// Если источников несколько, то выполняем параллельную агрегацию
|
2012-05-09 13:12:38 +00:00
|
|
|
|
if (streams.size() > 1)
|
|
|
|
|
{
|
2013-09-01 04:55:41 +00:00
|
|
|
|
stream = maybeAsynchronous(new ParallelAggregatingBlockInputStream(streams, key_names, aggregates, query.group_by_with_totals, separate_totals,
|
2013-05-04 15:46:50 +00:00
|
|
|
|
settings.max_threads, settings.limits.max_rows_to_group_by, settings.limits.group_by_overflow_mode), settings.asynchronous);
|
2012-05-09 13:12:38 +00:00
|
|
|
|
streams.resize(1);
|
2013-09-15 10:53:10 +00:00
|
|
|
|
|
|
|
|
|
/* stream = maybeAsynchronous(
|
|
|
|
|
new SplittingAggregatingBlockInputStream(
|
|
|
|
|
new UnionBlockInputStream(streams, settings.max_threads), key_names, aggregates, settings.max_threads),
|
|
|
|
|
settings.asynchronous);
|
|
|
|
|
|
|
|
|
|
streams.resize(1);*/
|
2011-11-06 22:00:39 +00:00
|
|
|
|
}
|
2012-05-09 13:12:38 +00:00
|
|
|
|
else
|
2013-09-01 04:55:41 +00:00
|
|
|
|
stream = maybeAsynchronous(new AggregatingBlockInputStream(stream, key_names, aggregates, query.group_by_with_totals, separate_totals,
|
2012-12-25 19:28:59 +00:00
|
|
|
|
settings.limits.max_rows_to_group_by, settings.limits.group_by_overflow_mode), settings.asynchronous);
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
2011-11-06 22:00:39 +00:00
|
|
|
|
|
2012-05-09 13:12:38 +00:00
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
void InterpreterSelectQuery::executeFinalizeAggregates(BlockInputStreams & streams)
|
2012-05-09 13:12:38 +00:00
|
|
|
|
{
|
2013-07-28 03:14:03 +00:00
|
|
|
|
Names key_names;
|
|
|
|
|
AggregateDescriptions aggregates;
|
|
|
|
|
query_analyzer->getAggregateInfo(key_names, aggregates);
|
|
|
|
|
|
2012-05-09 13:12:38 +00:00
|
|
|
|
/// Финализируем агрегатные функции - заменяем их состояния вычислений на готовые значения
|
|
|
|
|
BlockInputStreamPtr & stream = streams[0];
|
2013-07-28 03:14:03 +00:00
|
|
|
|
stream = maybeAsynchronous(new FinalizingAggregatedBlockInputStream(stream, aggregates), settings.asynchronous);
|
2012-05-30 01:38:02 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
void InterpreterSelectQuery::executeMergeAggregated(BlockInputStreams & streams)
|
2012-05-30 01:38:02 +00:00
|
|
|
|
{
|
|
|
|
|
/// Если объединять нечего
|
|
|
|
|
if (streams.size() == 1)
|
|
|
|
|
return;
|
|
|
|
|
|
|
|
|
|
/// Склеим несколько источников в один
|
2012-08-02 17:33:31 +00:00
|
|
|
|
streams[0] = new UnionBlockInputStream(streams, settings.max_threads);
|
2012-05-30 01:38:02 +00:00
|
|
|
|
streams.resize(1);
|
|
|
|
|
|
2013-09-01 04:55:41 +00:00
|
|
|
|
bool separate_totals = to_stage > QueryProcessingStage::WithMergeableState;
|
|
|
|
|
|
2012-05-30 01:38:02 +00:00
|
|
|
|
/// Теперь объединим агрегированные блоки
|
2013-05-27 14:02:55 +00:00
|
|
|
|
Names key_names;
|
|
|
|
|
AggregateDescriptions aggregates;
|
2013-06-03 10:18:41 +00:00
|
|
|
|
query_analyzer->getAggregateInfo(key_names, aggregates);
|
2013-09-01 04:55:41 +00:00
|
|
|
|
streams[0] = maybeAsynchronous(new MergingAggregatedBlockInputStream(streams[0], key_names, aggregates, query.group_by_with_totals, separate_totals), settings.asynchronous);
|
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
|
|
|
|
{
|
2013-06-03 10:18:41 +00:00
|
|
|
|
bool is_async = settings.asynchronous && streams.size() <= settings.max_threads;
|
|
|
|
|
for (BlockInputStreams::iterator it = streams.begin(); it != streams.end(); ++it)
|
2011-11-06 22:00:39 +00:00
|
|
|
|
{
|
2013-06-03 10:18:41 +00:00
|
|
|
|
BlockInputStreamPtr & stream = *it;
|
|
|
|
|
stream = maybeAsynchronous(new ExpressionBlockInputStream(stream, expression), is_async);
|
|
|
|
|
stream = maybeAsynchronous(new FilterBlockInputStream(stream, query.having_expression->getColumnName()), is_async);
|
2011-09-25 03:37:09 +00:00
|
|
|
|
}
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
|
|
|
|
|
2011-09-25 03:37:09 +00:00
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
void InterpreterSelectQuery::executeOuterExpression(BlockInputStreams & streams, ExpressionActionsPtr expression)
|
2012-05-09 13:12:38 +00:00
|
|
|
|
{
|
2012-08-02 17:33:31 +00:00
|
|
|
|
bool is_async = settings.asynchronous && streams.size() <= settings.max_threads;
|
2012-02-27 06:28:20 +00:00
|
|
|
|
for (BlockInputStreams::iterator it = streams.begin(); it != streams.end(); ++it)
|
|
|
|
|
{
|
|
|
|
|
BlockInputStreamPtr & stream = *it;
|
2013-06-03 10:18:41 +00:00
|
|
|
|
stream = maybeAsynchronous(new ExpressionBlockInputStream(stream, expression), is_async);
|
2012-02-27 06:28:20 +00:00
|
|
|
|
}
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
void InterpreterSelectQuery::executeOrder(BlockInputStreams & streams)
|
2012-05-09 13:12:38 +00:00
|
|
|
|
{
|
2013-06-03 10:18:41 +00:00
|
|
|
|
SortDescription order_descr;
|
|
|
|
|
order_descr.reserve(query.order_expression_list->children.size());
|
|
|
|
|
for (ASTs::iterator it = query.order_expression_list->children.begin();
|
|
|
|
|
it != query.order_expression_list->children.end();
|
|
|
|
|
++it)
|
2011-09-04 05:14:52 +00:00
|
|
|
|
{
|
2013-06-03 10:18:41 +00:00
|
|
|
|
String name = (*it)->children.front()->getColumnName();
|
|
|
|
|
order_descr.push_back(SortColumnDescription(name, dynamic_cast<ASTOrderByElement &>(**it).direction));
|
|
|
|
|
}
|
2011-09-04 05:14:52 +00:00
|
|
|
|
|
2013-09-16 05:44:47 +00:00
|
|
|
|
/// Если есть LIMIT - можно делать частичную сортировку.
|
|
|
|
|
size_t limit_length = 0;
|
|
|
|
|
size_t limit_offset = 0;
|
|
|
|
|
getLimitLengthAndOffset(query, limit_length, limit_offset);
|
|
|
|
|
size_t limit = limit_length + limit_offset;
|
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
bool is_async = settings.asynchronous && streams.size() <= settings.max_threads;
|
|
|
|
|
for (BlockInputStreams::iterator it = streams.begin(); it != streams.end(); ++it)
|
|
|
|
|
{
|
|
|
|
|
BlockInputStreamPtr & stream = *it;
|
2013-09-16 05:44:47 +00:00
|
|
|
|
IProfilingBlockInputStream * sorting_stream = new PartialSortingBlockInputStream(stream, order_descr, limit);
|
2013-06-03 10:18:41 +00:00
|
|
|
|
|
|
|
|
|
/// Ограничения на сортировку
|
|
|
|
|
IProfilingBlockInputStream::LocalLimits limits;
|
|
|
|
|
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);
|
2012-12-25 20:36:35 +00:00
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
stream = maybeAsynchronous(sorting_stream, is_async);
|
|
|
|
|
}
|
2012-02-27 06:28:20 +00:00
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
BlockInputStreamPtr & stream = streams[0];
|
2012-02-27 06:28:20 +00:00
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
/// Если потоков несколько, то объединяем их в один
|
|
|
|
|
if (streams.size() > 1)
|
|
|
|
|
{
|
|
|
|
|
stream = new UnionBlockInputStream(streams, settings.max_threads);
|
|
|
|
|
streams.resize(1);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Сливаем сортированные блоки TODO: таймаут на слияние.
|
2013-09-16 05:44:47 +00:00
|
|
|
|
stream = maybeAsynchronous(new MergeSortingBlockInputStream(stream, order_descr, limit), is_async);
|
2013-06-03 10:18:41 +00:00
|
|
|
|
}
|
2012-02-27 06:28:20 +00:00
|
|
|
|
|
2012-07-25 20:29:22 +00:00
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
void InterpreterSelectQuery::executeProjection(BlockInputStreams & streams, ExpressionActionsPtr expression)
|
|
|
|
|
{
|
|
|
|
|
bool is_async = settings.asynchronous && streams.size() <= settings.max_threads;
|
|
|
|
|
for (BlockInputStreams::iterator it = streams.begin(); it != streams.end(); ++it)
|
|
|
|
|
{
|
|
|
|
|
BlockInputStreamPtr & stream = *it;
|
|
|
|
|
stream = maybeAsynchronous(new ExpressionBlockInputStream(stream, expression), is_async);
|
2011-09-04 05:14:52 +00:00
|
|
|
|
}
|
2012-05-09 13:12:38 +00:00
|
|
|
|
}
|
|
|
|
|
|
2012-02-27 06:28:20 +00:00
|
|
|
|
|
2013-06-01 07:43:57 +00:00
|
|
|
|
void InterpreterSelectQuery::executeDistinct(BlockInputStreams & streams, bool before_order)
|
|
|
|
|
{
|
|
|
|
|
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;
|
|
|
|
|
|
|
|
|
|
bool is_async = settings.asynchronous && streams.size() <= settings.max_threads;
|
|
|
|
|
for (BlockInputStreams::iterator it = streams.begin(); it != streams.end(); ++it)
|
|
|
|
|
{
|
|
|
|
|
BlockInputStreamPtr & stream = *it;
|
2013-06-20 12:12:27 +00:00
|
|
|
|
stream = maybeAsynchronous(new DistinctBlockInputStream(stream, settings.limits, limit_for_distinct), is_async);
|
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
|
|
|
|
{
|
2012-02-27 06:28:20 +00:00
|
|
|
|
/// Если до сих пор есть несколько потоков, то объединяем их в один
|
|
|
|
|
if (streams.size() > 1)
|
|
|
|
|
{
|
2012-08-02 17:33:31 +00:00
|
|
|
|
streams[0] = new UnionBlockInputStream(streams, settings.max_threads);
|
2012-02-27 06:28:20 +00:00
|
|
|
|
streams.resize(1);
|
|
|
|
|
}
|
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
|
|
|
|
{
|
|
|
|
|
size_t limit_length = 0;
|
|
|
|
|
size_t limit_offset = 0;
|
|
|
|
|
getLimitLengthAndOffset(query, limit_length, limit_offset);
|
2012-02-27 06:28:20 +00:00
|
|
|
|
|
2012-06-24 23:17:06 +00:00
|
|
|
|
/// Если есть LIMIT
|
|
|
|
|
if (query.limit_length)
|
|
|
|
|
{
|
|
|
|
|
for (BlockInputStreams::iterator it = streams.begin(); it != streams.end(); ++it)
|
|
|
|
|
{
|
|
|
|
|
BlockInputStreamPtr & stream = *it;
|
|
|
|
|
stream = new LimitBlockInputStream(stream, limit_length + limit_offset, 0);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2013-06-03 10:18:41 +00:00
|
|
|
|
void InterpreterSelectQuery::executeLimit(BlockInputStreams & streams)
|
2012-06-24 23:17:06 +00:00
|
|
|
|
{
|
|
|
|
|
size_t limit_length = 0;
|
|
|
|
|
size_t limit_offset = 0;
|
|
|
|
|
getLimitLengthAndOffset(query, limit_length, limit_offset);
|
2012-05-09 13:12:38 +00:00
|
|
|
|
|
2011-08-28 08:02:11 +00:00
|
|
|
|
/// Если есть LIMIT
|
|
|
|
|
if (query.limit_length)
|
|
|
|
|
{
|
2012-06-24 23:17:06 +00:00
|
|
|
|
BlockInputStreamPtr & stream = streams[0];
|
2011-08-28 08:02:11 +00:00
|
|
|
|
stream = new LimitBlockInputStream(stream, limit_length, limit_offset);
|
|
|
|
|
}
|
2011-08-28 05:13:24 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2011-10-30 05:19:41 +00:00
|
|
|
|
BlockInputStreamPtr InterpreterSelectQuery::executeAndFormat(WriteBuffer & buf)
|
|
|
|
|
{
|
|
|
|
|
Block sample = getSampleBlock();
|
2013-06-29 18:03:57 +00:00
|
|
|
|
String format_name = query.format ? dynamic_cast<ASTIdentifier &>(*query.format).name : context.getDefaultFormat();
|
2011-10-30 05:19:41 +00:00
|
|
|
|
|
|
|
|
|
BlockInputStreamPtr in = execute();
|
2013-05-22 14:57:43 +00:00
|
|
|
|
BlockOutputStreamPtr out = context.getFormatFactory().getOutput(format_name, buf, sample);
|
2013-05-31 17:34:30 +00:00
|
|
|
|
|
2011-10-30 05:19:41 +00:00
|
|
|
|
copyData(*in, *out);
|
|
|
|
|
|
|
|
|
|
return in;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2011-08-28 05:13:24 +00:00
|
|
|
|
}
|