Skip to content

Commit

Permalink
translate comments
Browse files Browse the repository at this point in the history
  • Loading branch information
f1yegor authored and alexey-milovidov committed May 14, 2017
1 parent 043717e commit c252863
Show file tree
Hide file tree
Showing 81 changed files with 637 additions and 635 deletions.
2 changes: 1 addition & 1 deletion dbms/src/DataStreams/AddingConstColumnBlockInputStream.h
Expand Up @@ -7,7 +7,7 @@
namespace DB
{

/** Добавляет в блок материализованный const column с заданным значением.
/** Adds a materialized const column to the block with a specified value.
*/
template <typename ColumnType>
class AddingConstColumnBlockInputStream : public IProfilingBlockInputStream
Expand Down
4 changes: 2 additions & 2 deletions dbms/src/DataStreams/AddingDefaultBlockInputStream.h
Expand Up @@ -11,8 +11,8 @@ namespace DB
{


/** Добавляет в блок недостающие столбцы со значениями по-умолчанию.
* Эти столбцы - материалированные (не константы).
/** Adds missing columns to the block with default values.
* These columns are materialized (not constants).
*/
class AddingDefaultBlockInputStream : public IProfilingBlockInputStream
{
Expand Down
4 changes: 2 additions & 2 deletions dbms/src/DataStreams/AddingDefaultBlockOutputStream.h
Expand Up @@ -11,8 +11,8 @@ namespace DB
{


/** Добавляет в блок недостающие столбцы со значениями по-умолчанию.
* Эти столбцы - материалированные (не константы).
/** Adds missing columns to the block with default values.
* These columns are materialized (not constants).
*/
class AddingDefaultBlockOutputStream : public IBlockOutputStream
{
Expand Down
18 changes: 9 additions & 9 deletions dbms/src/DataStreams/AggregatingBlockInputStream.h
Expand Up @@ -10,17 +10,17 @@ namespace DB
{


/** Агрегирует поток блоков, используя заданные столбцы-ключи и агрегатные функции.
* Столбцы с агрегатными функциями добавляет в конец блока.
* Если final=false, агрегатные функции не финализируются, то есть, не заменяются на своё значение, а содержат промежуточное состояние вычислений.
* Это необходимо, чтобы можно было продолжить агрегацию (например, объединяя потоки частично агрегированных данных).
/** Aggregates the stream of blocks using the specified key columns and aggregate functions.
* Columns with aggregate functions adds to the end of the block.
* If final = false, the aggregate functions are not finalized, that is, they are not replaced by their value, but contain an intermediate state of calculations.
* This is necessary so that aggregation can continue (for example, by combining streams of partially aggregated data).
*/
class AggregatingBlockInputStream : public IProfilingBlockInputStream
{
public:
/** keys берутся из GROUP BY части запроса
* Агрегатные функции ищутся везде в выражении.
* Столбцы, соответствующие keys и аргументам агрегатных функций, уже должны быть вычислены.
/** keys are taken from the GROUP BY part of the query
* Aggregate functions are searched everywhere in the expression.
* Columns corresponding to keys and arguments of aggregate functions must already be computed.
*/
AggregatingBlockInputStream(BlockInputStreamPtr input_, const Aggregator::Params & params_, bool final_)
: params(params_), aggregator(params), final(final_)
Expand All @@ -46,7 +46,7 @@ class AggregatingBlockInputStream : public IProfilingBlockInputStream

bool executed = false;

/// Для чтения сброшенных во временный файл данных.
/// To read the data that was flushed into the temporary data file.
struct TemporaryFileStream
{
ReadBufferFromFile file_in;
Expand All @@ -57,7 +57,7 @@ class AggregatingBlockInputStream : public IProfilingBlockInputStream
};
std::vector<std::unique_ptr<TemporaryFileStream>> temporary_inputs;

/** Отсюда будем доставать готовые блоки после агрегации. */
/** From here we will get the completed blocks after the aggregation. */
std::unique_ptr<IBlockInputStream> impl;

Logger * log = &Logger::get("AggregatingBlockInputStream");
Expand Down
26 changes: 13 additions & 13 deletions dbms/src/DataStreams/AggregatingSortedBlockInputStream.h
Expand Up @@ -12,11 +12,11 @@
namespace DB
{

/** Соединяет несколько сортированных потоков в один.
* При этом, для каждой группы идущих подряд одинаковых значений первичного ключа (столбцов, по которым сортируются данные),
* сливает их в одну строку. При слиянии, производится доагрегация данных - слияние состояний агрегатных функций,
* соответствующих одному значению первичного ключа. Для столбцов, не входящих в первичный ключ, и не имеющих тип AggregateFunction,
* при слиянии, выбирается первое попавшееся значение.
/** Merges several sorted streams to one.
* During this for each group of consecutive identical values of the primary key (the columns by which the data is sorted),
* merges them into one row. When merging, the data is pre-aggregated - merge of states of aggregate functions,
* corresponding to a one value of the primary key. For columns that are not part of the primary key and which do not have the AggregateFunction type,
* when merged, the first random value is selected.
*/
class AggregatingSortedBlockInputStream : public MergingSortedBlockInputStream
{
Expand Down Expand Up @@ -50,30 +50,30 @@ class AggregatingSortedBlockInputStream : public MergingSortedBlockInputStream
const SortDescription & getSortDescription() const override { return description; }

protected:
/// Может возвращаться на 1 больше записей, чем max_block_size.
/// Can return 1 more records than max_block_size.
Block readImpl() override;

private:
Logger * log = &Logger::get("AggregatingSortedBlockInputStream");

/// Прочитали до конца.
/// Read finished.
bool finished = false;

/// Столбцы с какими номерами надо аггрегировать.
/// Columns with which numbers should be aggregated.
ColumnNumbers column_numbers_to_aggregate;
ColumnNumbers column_numbers_not_to_aggregate;
std::vector<ColumnAggregateFunction *> columns_to_aggregate;

RowRef current_key; /// Текущий первичный ключ.
RowRef next_key; /// Первичный ключ следующей строки.
RowRef current_key; /// The current primary key.
RowRef next_key; /// The primary key of the next row.

/** Делаем поддержку двух разных курсоров - с Collation и без.
* Шаблоны используем вместо полиморфных SortCursor'ов и вызовов виртуальных функций.
/** We support two different cursors - with Collation and without.
* Templates are used instead of polymorphic SortCursor and calls to virtual functions.
*/
template <class TSortCursor>
void merge(ColumnPlainPtrs & merged_columns, std::priority_queue<TSortCursor> & queue);

/** Извлечь все состояния аггрегатных функций и объединить с текущей группой.
/** Extract all states of aggregate functions and merge them with the current group.
*/
template <class TSortCursor>
void addRow(TSortCursor & cursor);
Expand Down
27 changes: 14 additions & 13 deletions dbms/src/DataStreams/AsynchronousBlockInputStream.h
Expand Up @@ -17,12 +17,13 @@ namespace CurrentMetrics
namespace DB
{

/** Выполняет другой BlockInputStream в отдельном потоке.
* Это служит для двух целей:
* 1. Позволяет сделать так, чтобы разные стадии конвейера выполнения запроса работали параллельно.
* 2. Позволяет не ждать до того, как данные будут готовы, а периодически проверять их готовность без блокировки.
* Это нужно, например, чтобы можно было во время ожидания проверить, не пришёл ли по сети пакет с просьбой прервать выполнение запроса.
* Также это позволяет выполнить несколько запросов одновременно.
/** Executes another BlockInputStream in a separate thread.
* This serves two purposes:
* 1. Allows you to make the different stages of the query execution pipeline work in parallel.
* 2. Allows you not to wait until the data is ready, and periodically check their readiness without blocking.
* This is necessary, for example, so that during the waiting period you can check if a packet
* has come over the network with a request to interrupt the execution of the query.
* It also allows you to execute multiple queries at the same time.
*/
class AsynchronousBlockInputStream : public IProfilingBlockInputStream
{
Expand All @@ -43,7 +44,7 @@ class AsynchronousBlockInputStream : public IProfilingBlockInputStream

void readPrefix() override
{
/// Не будем вызывать readPrefix у ребёнка, чтобы соответствующие действия совершались в отдельном потоке.
/// Do not call `readPrefix` on the child, so that the corresponding actions are performed in a separate thread.
if (!started)
{
next();
Expand All @@ -64,8 +65,8 @@ class AsynchronousBlockInputStream : public IProfilingBlockInputStream
}


/** Ждать готовность данных не более заданного таймаута. Запустить получение данных, если нужно.
* Если функция вернула true - данные готовы и можно делать read(); нельзя вызвать функцию сразу ещё раз.
/** Wait for the data to be ready no more than the specified timeout. Start receiving data if necessary.
* If the function returned true - the data is ready and you can do `read()`; You can not call the function just at the same moment again.
*/
bool poll(UInt64 milliseconds)
{
Expand Down Expand Up @@ -97,13 +98,13 @@ class AsynchronousBlockInputStream : public IProfilingBlockInputStream

Block readImpl() override
{
/// Если вычислений ещё не было - вычислим первый блок синхронно
/// If there were no calculations yet, calculate the first block synchronously
if (!started)
{
calculate(current_memory_tracker);
started = true;
}
else /// Если вычисления уже идут - подождём результата
else /// If the calculations are already in progress - wait for the result
pool.wait();

if (exception)
Expand All @@ -113,7 +114,7 @@ class AsynchronousBlockInputStream : public IProfilingBlockInputStream
if (!res)
return res;

/// Запустим вычисления следующего блока
/// Start the next block calculation
block = Block();
next();

Expand All @@ -128,7 +129,7 @@ class AsynchronousBlockInputStream : public IProfilingBlockInputStream
}


/// Вычисления, которые могут выполняться в отдельном потоке
/// Calculations that can be performed in a separate thread
void calculate(MemoryTracker * memory_tracker)
{
CurrentMetrics::Increment metric_increment{CurrentMetrics::QueryThread};
Expand Down
2 changes: 1 addition & 1 deletion dbms/src/DataStreams/BinaryRowInputStream.h
Expand Up @@ -10,7 +10,7 @@ class Block;
class ReadBuffer;


/** Поток для ввода данных в бинарном построчном формате.
/** A stream for inputting data in a binary line-by-line format.
*/
class BinaryRowInputStream : public IRowInputStream
{
Expand Down
2 changes: 1 addition & 1 deletion dbms/src/DataStreams/BinaryRowOutputStream.h
Expand Up @@ -11,7 +11,7 @@ class IDataType;
class WriteBuffer;


/** Поток для вывода данных в бинарном построчном формате.
/** A stream for outputting data in a binary line-by-line format.
*/
class BinaryRowOutputStream : public IRowOutputStream
{
Expand Down
4 changes: 2 additions & 2 deletions dbms/src/DataStreams/BlockExtraInfoInputStream.h
Expand Up @@ -5,8 +5,8 @@
namespace DB
{

/** Прибавляет к одному потоку дополнительную информацию о блоках, которая задана
* в качестве параметра конструктора.
/** Adds to one thread additional block information that is specified
* as the constructor parameter.
*/
class BlockExtraInfoInputStream : public IProfilingBlockInputStream
{
Expand Down
8 changes: 4 additions & 4 deletions dbms/src/DataStreams/BlockIO.h
Expand Up @@ -21,14 +21,14 @@ struct BlockIO
BlockInputStreamPtr in;
BlockOutputStreamPtr out;

Block in_sample; /// Пример блока, который будет прочитан из in.
Block out_sample; /// Пример блока, которого нужно писать в out.
Block in_sample; /// Example of a block to be read from `in`.
Block out_sample; /// Example of a block to be written to `out`.

/// Callbacks for query logging could be set here.
std::function<void(IBlockInputStream *, IBlockOutputStream *)> finish_callback;
std::function<void()> exception_callback;

/// Вызывайте эти функции, если нужно логгировать запрос.
/// Call these functions if you want to log the request.
void onFinish()
{
if (finish_callback)
Expand All @@ -43,7 +43,7 @@ struct BlockIO

BlockIO & operator= (const BlockIO & rhs)
{
/// Обеспечиваем правильный порядок уничтожения.
/// We provide the correct order of destruction.
out = nullptr;
in = nullptr;
process_list_entry = nullptr;
Expand Down
4 changes: 2 additions & 2 deletions dbms/src/DataStreams/BlockOutputStreamFromRowOutputStream.h
Expand Up @@ -7,8 +7,8 @@
namespace DB
{

/** Преобразует поток для записи данных по строкам в поток для записи данных по блокам.
* Наример, для записи текстового дампа.
/** Transforms a stream to write data by rows to a stream to write data by blocks.
* For example, to write a text dump.
*/
class BlockOutputStreamFromRowOutputStream : public IBlockOutputStream
{
Expand Down
24 changes: 12 additions & 12 deletions dbms/src/DataStreams/BlockStreamProfileInfo.h
Expand Up @@ -16,29 +16,29 @@ class Block;
class ReadBuffer;
class WriteBuffer;

/// Информация для профайлинга. См. IProfilingBlockInputStream.h
/// Information for profiling. See IProfilingBlockInputStream.h
struct BlockStreamProfileInfo
{
bool started = false;
Stopwatch total_stopwatch {CLOCK_MONOTONIC_COARSE}; /// Время с учётом ожидания
Stopwatch total_stopwatch {CLOCK_MONOTONIC_COARSE}; /// Time with waiting time

String stream_name; /// Короткое имя потока, для которого собирается информация
String stream_name; /// The short name of the stream for which information is collected

size_t rows = 0;
size_t blocks = 0;
size_t bytes = 0;

/// Информация о вложенных потоках - для выделения чистого времени работы.
/// Information about nested threads - to calculate pure processing time.
using BlockStreamProfileInfos = std::vector<const BlockStreamProfileInfo *>;
BlockStreamProfileInfos nested_infos;

/// Собрать BlockStreamProfileInfo для ближайших в дереве источников с именем name. Пример; собрать все info для PartialSorting stream-ов.
/// Collect BlockStreamProfileInfo for the nearest sources in the tree named `name`. Example; collect all info for PartialSorting streams.
void collectInfosForStreamsWithName(const char * name, BlockStreamProfileInfos & res) const;

/** Получить число строк, если бы не было LIMIT.
* Если нет LIMIT-а - возвращается 0.
* Если запрос не содержит ORDER BY, то число может быть занижено - возвращается количество строк в блоках, которые были прочитаны до LIMIT.
* Если запрос содержит ORDER BY, то возвращается точное число строк, которое было бы, если убрать LIMIT.
/** Get the number of rows if there were no LIMIT.
* If there is no LIMIT, 0 is returned.
* If the query does not contain ORDER BY, the number can be underestimated - return the number of rows in blocks that were read before LIMIT reached.
* If the query contains an ORDER BY, then returns the exact number of rows as if LIMIT is removed from query.
*/
size_t getRowsBeforeLimit() const;
bool hasAppliedLimit() const;
Expand All @@ -57,10 +57,10 @@ struct BlockStreamProfileInfo
private:
void calculateRowsBeforeLimit() const;

/// Для этих полей сделаем accessor'ы, т.к. их необходимо предварительно вычислять.
mutable bool applied_limit = false; /// Применялся ли LIMIT
/// For these fields we make accessors, because they must be calculated beforehand.
mutable bool applied_limit = false; /// Whether LIMIT was applied
mutable size_t rows_before_limit = 0;
mutable bool calculated_rows_before_limit = false; /// Вычислялось ли поле rows_before_limit
mutable bool calculated_rows_before_limit = false; /// Whether the field rows_before_limit was calculated
};

}
8 changes: 4 additions & 4 deletions dbms/src/DataStreams/BlocksListBlockInputStream.h
Expand Up @@ -6,17 +6,17 @@
namespace DB
{

/** Поток блоков, из которого можно прочитать следующий блок из явно предоставленного списка.
* Также смотрите OneBlockInputStream.
/** A stream of blocks from which you can read the next block from an explicitly provided list.
* Also see OneBlockInputStream.
*/
class BlocksListBlockInputStream : public IProfilingBlockInputStream
{
public:
/// Захватывает владение списком блоков.
/// Acquires the ownership of the block list.
BlocksListBlockInputStream(BlocksList && list_)
: list(std::move(list_)), it(list.begin()), end(list.end()) {}

/// Использует лежащий где-то ещё список блоков.
/// Uses a list of blocks lying somewhere else.
BlocksListBlockInputStream(BlocksList::iterator & begin_, BlocksList::iterator & end_)
: it(begin_), end(end_) {}

Expand Down

0 comments on commit c252863

Please sign in to comment.