FunctionsMiscellaneous.h 32.9 KB
Newer Older
A
Alexey Milovidov 已提交
1 2
#pragma once

3 4
#include <Poco/Net/DNS.h>

A
Alexey Milovidov 已提交
5 6
#include <math.h>

7
#include <DB/IO/WriteBufferFromString.h>
A
Alexey Milovidov 已提交
8 9 10 11 12
#include <DB/DataTypes/DataTypesNumberFixed.h>
#include <DB/DataTypes/DataTypeString.h>
#include <DB/DataTypes/DataTypeFixedString.h>
#include <DB/DataTypes/DataTypeDate.h>
#include <DB/DataTypes/DataTypeDateTime.h>
13
#include <DB/DataTypes/DataTypeTuple.h>
14
#include <DB/DataTypes/DataTypeArray.h>
A
Alexey Milovidov 已提交
15 16 17 18
#include <DB/Columns/ColumnString.h>
#include <DB/Columns/ColumnFixedString.h>
#include <DB/Columns/ColumnConst.h>
#include <DB/Columns/ColumnVector.h>
19
#include <DB/Columns/ColumnSet.h>
20
#include <DB/Columns/ColumnTuple.h>
21
#include <DB/Columns/ColumnArray.h>
22
#include <DB/Columns/ColumnReplicated.h>
23
#include <DB/Common/UnicodeBar.h>
A
Alexey Milovidov 已提交
24
#include <DB/Functions/IFunction.h>
25
#include <DB/Interpreters/ExpressionActions.h>
26
#include <statdaemons/ext/range.hpp>
A
Alexey Milovidov 已提交
27 28 29 30 31 32 33


namespace DB
{

/** Вспомогательные функции:
  *
34
  * visibleWidth(x)	- вычисляет приблизительную ширину при выводе значения в текстовом (tab-separated) виде на консоль.
35
  *
36 37 38
  * toTypeName(x)	- получить имя типа
  * blockSize()		- получить размер блока
  * materialize(x)	- материализовать константу
39
  * ignore(...)		- функция, принимающая любые аргументы, и всегда возвращающая 0.
40
  * sleep(seconds)	- спит указанное количество секунд каждый блок.
41
  *
42 43
  * in(x, set)		- функция для вычисления оператора IN
  * notIn(x, set)	-  и NOT IN.
44 45
  *
  * tuple(x, y, ...) - функция, позволяющая сгруппировать несколько столбцов
46
  * tupleElement(tuple, n) - функция, позволяющая достать столбец из tuple.
47
  *
48
  * arrayJoin(arr)	- особая функция - выполнить её напрямую нельзя;
49
  *                   используется только чтобы получить тип результата соответствующего выражения.
50 51 52 53 54
  *
  * replicate(x, arr) - копирует x столько раз, сколько элементов в массиве arr;
  * 					например: replicate(1, ['a', 'b', 'c']) = 1, 1, 1.
  *                     не предназначена для пользователя, а используется только как prerequisites для функций высшего порядка.
  *
55
  * sleep(n)		- спит n секунд каждый блок.
56 57
  *
  * bar(x, min, max, width) - рисует полосу из количества символов, пропорционального (x - min) и равного width при x == max.
A
Alexey Milovidov 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
  */


static inline UInt64 stringWidth(const UInt8 * pos, const UInt8 * end)
{
	UInt64 res = 0;
 	for (; pos < end; ++pos)
	{
		if (*pos == '\b' || *pos == '\f' || *pos == '\n' || *pos == '\r' || *pos == '\t' || *pos == '\0' || *pos == '\'' || *pos == '\\')
			++res;
		if (*pos <= 0x7F || *pos >= 0xC0)
			++res;
	}
	return res;
}

74
static inline void stringWidthConstant(const String & data, UInt64 & res)
A
Alexey Milovidov 已提交
75 76 77 78
{
	res = stringWidth(reinterpret_cast<const UInt8 *>(data.data()), reinterpret_cast<const UInt8 *>(data.data()) + data.size());
}

79 80
class FunctionCurrentDatabase : public IFunction
{
81
	const String db_name;
82 83

public:
84 85 86 87
	static constexpr auto name = "currentDatabase";
	static IFunction * create(const Context & context) { return new FunctionCurrentDatabase{context.getCurrentDatabase()}; }

	explicit FunctionCurrentDatabase(const String & db_name) : db_name{db_name} {}
88 89

	String getName() const {
90
		return name;
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
	}

	DataTypePtr getReturnType(const DataTypes & arguments) const
	{
		if (arguments.size() != 0)
			throw Exception("Number of arguments for function " + getName() + " doesn't match: passed "
				+ toString(arguments.size()) + ", should be 0.",
				ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

		return new DataTypeString;
	}

	void execute(Block & block, const ColumnNumbers & arguments, const size_t result)
	{
		block.getByPosition(result).column = new ColumnConstString{
106
			block.rowsInFirstColumn(), db_name
107 108 109 110
		};
	}
};

111

112 113 114 115
/// Получить имя хоста. (Оно - константа, вычисляется один раз за весь запрос.)
class FunctionHostName : public IFunction
{
public:
116 117 118
	static constexpr auto name = "hostName";
	static IFunction * create(const Context & context) { return new FunctionHostName; }

119 120 121
	/// Получить имя функции.
	String getName() const
	{
122
		return name;
123 124 125 126 127 128 129 130 131 132 133 134 135
	}

	/// Получить тип результата по типам аргументов. Если функция неприменима для данных аргументов - кинуть исключение.
	DataTypePtr getReturnType(const DataTypes & arguments) const
	{
		if (arguments.size() != 0)
			throw Exception("Number of arguments for function " + getName() + " doesn't match: passed "
				+ toString(arguments.size()) + ", should be 0.",
				ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

		return new DataTypeString;
	}

136 137
	/** Выполнить функцию над блоком. convertToFullColumn вызывается для того, чтобы в случае
	 *	распределенного выполнения запроса каждый сервер возвращал свое имя хоста. */
138 139
	void execute(Block & block, const ColumnNumbers & arguments, size_t result)
	{
A
Alexey Milovidov 已提交
140
		block.getByPosition(result).column = ColumnConstString(
141
			block.rowsInFirstColumn(),
A
Alexey Milovidov 已提交
142
			Poco::Net::DNS::hostName()).convertToFullColumn();
143 144
	}
};
A
Alexey Milovidov 已提交
145

146

A
Alexey Milovidov 已提交
147 148 149
class FunctionVisibleWidth : public IFunction
{
public:
150 151 152
	static constexpr auto name = "visibleWidth";
	static IFunction * create(const Context & context) { return new FunctionVisibleWidth; }

A
Alexey Milovidov 已提交
153 154 155
	/// Получить имя функции.
	String getName() const
	{
156
		return name;
A
Alexey Milovidov 已提交
157 158 159 160 161 162 163
	}

	/// Получить тип результата по типам аргументов. Если функция неприменима для данных аргументов - кинуть исключение.
	DataTypePtr getReturnType(const DataTypes & arguments) const
	{
		if (arguments.size() != 1)
			throw Exception("Number of arguments for function " + getName() + " doesn't match: passed "
164
				+ toString(arguments.size()) + ", should be 1.",
A
Alexey Milovidov 已提交
165 166 167 168 169 170
				ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

		return new DataTypeUInt64;
	}

	/// Выполнить функцию над блоком.
171
	void execute(Block & block, const ColumnNumbers & arguments, size_t result);
A
Alexey Milovidov 已提交
172 173
};

174 175 176 177

class FunctionToTypeName : public IFunction
{
public:
178 179 180
	static constexpr auto name = "toTypeName";
	static IFunction * create(const Context & context) { return new FunctionToTypeName; }

181 182 183
	/// Получить имя функции.
	String getName() const
	{
184
		return name;
185 186 187 188 189
	}

	/// Получить тип результата по типам аргументов. Если функция неприменима для данных аргументов - кинуть исключение.
	DataTypePtr getReturnType(const DataTypes & arguments) const
	{
190
		if (arguments.size() != 1)
191
			throw Exception("Number of arguments for function " + getName() + " doesn't match: passed "
192
				+ toString(arguments.size()) + ", should be 1.",
193 194 195 196 197 198 199 200
				ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

		return new DataTypeString;
	}

	/// Выполнить функцию над блоком.
	void execute(Block & block, const ColumnNumbers & arguments, size_t result)
	{
201
		block.getByPosition(result).column = new ColumnConstString(block.rowsInFirstColumn(), block.getByPosition(arguments[0]).type->getName());
202 203 204
	}
};

205 206 207 208

class FunctionBlockSize : public IFunction
{
public:
209 210 211
	static constexpr auto name = "blockSize";
	static IFunction * create(const Context & context) { return new FunctionBlockSize; }

212 213 214
	/// Получить имя функции.
	String getName() const
	{
215
		return name;
216 217 218 219 220 221 222
	}

	/// Получить тип результата по типам аргументов. Если функция неприменима для данных аргументов - кинуть исключение.
	DataTypePtr getReturnType(const DataTypes & arguments) const
	{
		if (!arguments.empty())
			throw Exception("Number of arguments for function " + getName() + " doesn't match: passed "
223
				+ toString(arguments.size()) + ", should be 0.",
224 225 226 227 228 229 230 231
				ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

		return new DataTypeUInt64;
	}

	/// Выполнить функцию над блоком.
	void execute(Block & block, const ColumnNumbers & arguments, size_t result)
	{
232
		size_t size = block.rowsInFirstColumn();
233
		block.getByPosition(result).column = ColumnConstUInt64(size, size).convertToFullColumn();
234 235 236 237
	}
};


238 239 240
class FunctionSleep : public IFunction
{
public:
241 242 243
	static constexpr auto name = "sleep";
	static IFunction * create(const Context & context) { return new FunctionSleep; }

244 245 246
	/// Получить имя функции.
	String getName() const
	{
247
		return name;
248
	}
249

250 251 252 253 254
	/// Получить тип результата по типам аргументов. Если функция неприменима для данных аргументов - кинуть исключение.
	DataTypePtr getReturnType(const DataTypes & arguments) const
	{
		if (arguments.size() != 1)
			throw Exception("Number of arguments for function " + getName() + " doesn't match: passed "
255
			+ toString(arguments.size()) + ", should be 1.",
256
							ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);
257 258 259 260 261 262 263

		if (!typeid_cast<const DataTypeFloat64 *>(&*arguments[0]) &&
			!typeid_cast<const DataTypeFloat32 *>(&*arguments[0]) &&
			!typeid_cast<const DataTypeUInt64 *>(&*arguments[0]) &&
			!typeid_cast<const DataTypeUInt32 *>(&*arguments[0]) &&
			!typeid_cast<const DataTypeUInt16 *>(&*arguments[0]) &&
			!typeid_cast<const DataTypeUInt8 *>(&*arguments[0]))
264 265
			throw Exception("Illegal type " + arguments[0]->getName() + " of argument of function " + getName() + ", expected Float64",
			ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);
266

267 268
		return new DataTypeUInt8;
	}
269

270 271 272
	/// Выполнить функцию над блоком.
	void execute(Block & block, const ColumnNumbers & arguments, size_t result)
	{
273 274
		IColumn * col = &*block.getByPosition(arguments[0]).column;
		double seconds;
275
		size_t size = col->size();
276 277

		if (ColumnConst<Float64> * column = typeid_cast<ColumnConst<Float64> *>(col))
278
			seconds = column->getData();
279 280

		else if (ColumnConst<Float32> * column = typeid_cast<ColumnConst<Float32> *>(col))
281
			seconds = static_cast<double>(column->getData());
282 283

		else if (ColumnConst<UInt64> * column = typeid_cast<ColumnConst<UInt64> *>(col))
284
			seconds = static_cast<double>(column->getData());
285 286

		else if (ColumnConst<UInt32> * column = typeid_cast<ColumnConst<UInt32> *>(col))
287
			seconds = static_cast<double>(column->getData());
288 289

		else if (ColumnConst<UInt16> * column = typeid_cast<ColumnConst<UInt16> *>(col))
290
			seconds = static_cast<double>(column->getData());
291 292

		else if (ColumnConst<UInt8> * column = typeid_cast<ColumnConst<UInt8> *>(col))
293
			seconds = static_cast<double>(column->getData());
294

295
		else
296
			throw Exception("The argument of function " + getName() + " must be constant.", ErrorCodes::ILLEGAL_COLUMN);
297

298 299 300
		/// Не спим, если блок пустой.
		if (size > 0)
			usleep(static_cast<unsigned>(seconds * 1e6));
301

302
		block.getByPosition(result).column = ColumnConst<UInt8>(size, 0).convertToFullColumn();
303 304 305 306
	}
};


307 308 309
class FunctionMaterialize : public IFunction
{
public:
310 311 312
	static constexpr auto name = "materialize";
	static IFunction * create(const Context & context) { return new FunctionMaterialize; }

313 314 315
	/// Получить имя функции.
	String getName() const
	{
316
		return name;
317 318 319 320 321 322 323
	}

	/// Получить тип результата по типам аргументов. Если функция неприменима для данных аргументов - кинуть исключение.
	DataTypePtr getReturnType(const DataTypes & arguments) const
	{
		if (arguments.size() != 1)
			throw Exception("Number of arguments for function " + getName() + " doesn't match: passed "
324
				+ toString(arguments.size()) + ", should be 1.",
325 326 327 328 329 330 331 332 333 334
				ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

		return arguments[0];
	}

	/// Выполнить функцию над блоком.
	void execute(Block & block, const ColumnNumbers & arguments, size_t result)
	{
		const IColumn & argument = *block.getByPosition(arguments[0]).column;
		if (!argument.isConst())
335
			throw Exception("Argument for function " + getName() + " must be constant.", ErrorCodes::ILLEGAL_COLUMN);
336

337 338 339 340
		block.getByPosition(result).column = dynamic_cast<const IColumnConst &>(argument).convertToFullColumn();
	}
};

341 342 343 344 345
template <bool negative, bool global> struct FunctionInName;
template <> struct FunctionInName<false, false>	{ static constexpr auto name = "in"; };
template <> struct FunctionInName<false, true>	{ static constexpr auto name = "globalIn"; };
template <> struct FunctionInName<true, false>	{ static constexpr auto name = "notIn"; };
template <> struct FunctionInName<true, true>	{ static constexpr auto name = "globalNotIn"; };
346

347
template <bool negative, bool global>
348 349 350
class FunctionIn : public IFunction
{
public:
351 352
	static constexpr auto name = FunctionInName<negative, global>::name;
	static IFunction * create(const Context & context) { return new FunctionIn; }
353

354 355 356
	/// Получить имя функции.
	String getName() const
	{
357
		return name;
358 359 360 361 362 363
	}

	/// Получить тип результата по типам аргументов. Если функция неприменима для данных аргументов - кинуть исключение.
	DataTypePtr getReturnType(const DataTypes & arguments) const
	{
		if (arguments.size() != 2)
364
			throw Exception("Number of arguments for function '" + getName() + "' doesn't match: passed "
365
				+ toString(arguments.size()) + ", should be 2.",
366 367 368 369 370 371 372 373 374
				ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

		return new DataTypeUInt8;
	}

	/// Выполнить функцию над блоком.
	void execute(Block & block, const ColumnNumbers & arguments, size_t result)
	{
		/// Второй аргумент - обязательно ColumnSet.
375
		ColumnPtr column_set_ptr = block.getByPosition(arguments[1]).column;
376
		const ColumnSet * column_set = typeid_cast<const ColumnSet *>(&*column_set_ptr);
377
		if (!column_set)
378 379
			throw Exception("Second argument for function '" + getName() + "' must be Set; found " + column_set_ptr->getName(),
							ErrorCodes::ILLEGAL_COLUMN);
380

381 382
		/// Столбцы, которые проверяются на принадлежность множеству.
		ColumnNumbers left_arguments;
383

384
		/// Первый аргумент может быть tuple или одиночным столбцом.
385
		const ColumnTuple * tuple = typeid_cast<const ColumnTuple *>(&*block.getByPosition(arguments[0]).column);
386 387 388 389 390 391 392 393 394 395 396
		if (tuple)
		{
			/// Находим в блоке столбцы из tuple.
			const Block & tuple_elems = tuple->getData();
			size_t tuple_size = tuple_elems.columns();
			for (size_t i = 0; i < tuple_size; ++i)
				left_arguments.push_back(block.getPositionByName(tuple_elems.getByPosition(i).name));
		}
		else
			left_arguments.push_back(arguments[0]);

397
		column_set->getData()->execute(block, left_arguments, result, negative);
398 399 400 401 402 403 404
	}
};


class FunctionTuple : public IFunction
{
public:
405 406 407
	static constexpr auto name = "tuple";
	static IFunction * create(const Context & context) { return new FunctionTuple; }

408 409 410
	/// Получить имя функции.
	String getName() const
	{
411
		return name;
412 413 414 415 416 417
	}

	/// Получить тип результата по типам аргументов. Если функция неприменима для данных аргументов - кинуть исключение.
	DataTypePtr getReturnType(const DataTypes & arguments) const
	{
		if (arguments.size() < 2)
418
			throw Exception("Function " + getName() + " requires at least two arguments.", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);
419 420 421 422 423 424 425 426 427 428 429

		return new DataTypeTuple(arguments);
	}

	/// Выполнить функцию над блоком.
	void execute(Block & block, const ColumnNumbers & arguments, size_t result)
	{
		Block tuple_block;

		for (ColumnNumbers::const_iterator it = arguments.begin(); it != arguments.end(); ++it)
			tuple_block.insert(block.getByPosition(*it));
430

431
		block.getByPosition(result).column = new ColumnTuple(tuple_block);
432 433 434
	}
};

435 436 437 438

class FunctionTupleElement : public IFunction
{
public:
439 440 441
	static constexpr auto name = "tupleElement";
	static IFunction * create(const Context & context) { return new FunctionTupleElement; }

442 443 444
	/// Получить имя функции.
	String getName() const
	{
445
		return name;
446 447
	}

448
	void getReturnTypeAndPrerequisites(const ColumnsWithNameAndType & arguments,
449 450
										DataTypePtr & out_return_type,
										ExpressionActions::Actions & out_prerequisites)
451 452
	{
		if (arguments.size() != 2)
453
			throw Exception("Function " + getName() + " requires exactly two arguments: tuple and element index.",
454
							ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);
455 456

		const ColumnConstUInt8 * index_col = typeid_cast<const ColumnConstUInt8 *>(&*arguments[1].column);
457
		if (!index_col)
458
			throw Exception("Second argument to " + getName() + " must be a constant UInt8", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);
459

460
		size_t index = index_col->getData();
461 462

		const DataTypeTuple * tuple = typeid_cast<const DataTypeTuple *>(&*arguments[0].type);
463
		if (!tuple)
464
			throw Exception("First argument for function " + getName() + " must be tuple.", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);
465

466 467
		if (index == 0)
			throw Exception("Indices in tuples are 1-based.", ErrorCodes::ILLEGAL_INDEX);
468

469
		const DataTypes & elems = tuple->getElements();
470

471 472
		if (index > elems.size())
			throw Exception("Index for tuple element is out of range.", ErrorCodes::ILLEGAL_INDEX);
473

474 475
		out_return_type = elems[index - 1]->clone();
	}
476

477 478 479
	/// Выполнить функцию над блоком.
	void execute(Block & block, const ColumnNumbers & arguments, size_t result)
	{
480 481
		const ColumnTuple * tuple_col = typeid_cast<const ColumnTuple *>(&*block.getByPosition(arguments[0]).column);
		const ColumnConstUInt8 * index_col = typeid_cast<const ColumnConstUInt8 *>(&*block.getByPosition(arguments[1]).column);
482 483

		if (!tuple_col)
484
			throw Exception("First argument for function " + getName() + " must be tuple.", ErrorCodes::ILLEGAL_COLUMN);
485 486

		if (!index_col)
487
			throw Exception("Second argument for function " + getName() + " must be UInt8 constant literal.", ErrorCodes::ILLEGAL_COLUMN);
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505

		size_t index = index_col->getData();
		if (index == 0)
			throw Exception("Indices in tuples is 1-based.", ErrorCodes::ILLEGAL_INDEX);

		const Block & tuple_block = tuple_col->getData();

		if (index > tuple_block.columns())
			throw Exception("Index for tuple element is out of range.", ErrorCodes::ILLEGAL_INDEX);

		block.getByPosition(result).column = tuple_block.getByPosition(index - 1).column;
	}
};


class FunctionIgnore : public IFunction
{
public:
506 507 508
	static constexpr auto name = "ignore";
	static IFunction * create(const Context & context) { return new FunctionIgnore; }

509 510 511
	/// Получить имя функции.
	String getName() const
	{
512
		return name;
513 514 515 516 517 518 519 520 521 522 523
	}

	/// Получить тип результата по типам аргументов. Если функция неприменима для данных аргументов - кинуть исключение.
	DataTypePtr getReturnType(const DataTypes & arguments) const
	{
		return new DataTypeUInt8;
	}

	/// Выполнить функцию над блоком.
	void execute(Block & block, const ColumnNumbers & arguments, size_t result)
	{
524
		block.getByPosition(result).column = new ColumnConstUInt8(block.rowsInFirstColumn(), 0);
525 526 527
	}
};

528 529 530 531

class FunctionArrayJoin : public IFunction
{
public:
532 533 534 535
	static constexpr auto name = "arrayJoin";
	static IFunction * create(const Context & context) { return new FunctionArrayJoin; }


536 537 538
	/// Получить имя функции.
	String getName() const
	{
539
		return name;
540 541 542 543 544 545
	}

	/// Получить тип результата по типам аргументов. Если функция неприменима для данных аргументов - кинуть исключение.
	DataTypePtr getReturnType(const DataTypes & arguments) const
	{
		if (arguments.size() != 1)
546
			throw Exception("Function " + getName() + " requires exactly one argument.", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);
547

548
		const DataTypeArray * arr = typeid_cast<const DataTypeArray *>(&*arguments[0]);
549
		if (!arr)
550
			throw Exception("Argument for function " + getName() + " must be Array.", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);
551

552 553 554 555 556 557
		return arr->getNestedType()->clone();
	}

	/// Выполнить функцию над блоком.
	void execute(Block & block, const ColumnNumbers & arguments, size_t result)
	{
558
		throw Exception("Function " + getName() + " must not be executed directly.", ErrorCodes::FUNCTION_IS_SPECIAL);
559 560 561
	}
};

562 563 564 565 566 567 568

/** Размножает столбец (первый аргумент) по количеству элементов в массиве (втором аргументе).
  * Не предназначена для внешнего использования.
  * Так как возвращаемый столбец будет иметь несовпадающий размер с исходными,
  *  то результат не может быть потом использован в том же блоке, что и аргументы.
  * Используется только в качестве prerequisites для функций высшего порядка.
  */
569 570
class FunctionReplicate : public IFunction
{
571 572 573 574
	static constexpr auto name = "replicate";
	static IFunction * create(const Context & context) { return new FunctionReplicate; }


575 576 577
	/// Получить имя функции.
	String getName() const
	{
578
		return name;
579 580 581 582 583 584 585
	}

	/// Получить типы результата по типам аргументов. Если функция неприменима для данных аргументов - кинуть исключение.
	DataTypePtr getReturnType(const DataTypes & arguments) const
	{
		if (arguments.size() != 2)
			throw Exception("Number of arguments for function " + getName() + " doesn't match: passed "
586
							+ toString(arguments.size()) + ", should be 2.",
587 588
							ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

589
		const DataTypeArray * array_type = typeid_cast<const DataTypeArray *>(&*arguments[1]);
590 591 592
		if (!array_type)
			throw Exception("Second argument for function " + getName() + " must be array.", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);

593
		return arguments[0]->clone();
594 595 596 597 598 599
	}

	/// Выполнить функцию над блоком.
	void execute(Block & block, const ColumnNumbers & arguments, size_t result)
	{
		ColumnPtr first_column = block.getByPosition(arguments[0]).column;
600

601
		ColumnArray * array_column = typeid_cast<ColumnArray *>(&*block.getByPosition(arguments[1]).column);
602
		ColumnPtr temp_column;
603

604 605
		if (!array_column)
		{
606
			ColumnConstArray * const_array_column = typeid_cast<ColumnConstArray *>(&*block.getByPosition(arguments[1]).column);
607 608
			if (!const_array_column)
				throw Exception("Unexpected column for replicate", ErrorCodes::ILLEGAL_COLUMN);
609
			temp_column = const_array_column->convertToFullColumn();
610
			array_column = typeid_cast<ColumnArray *>(&*temp_column);
611
		}
612 613

		block.getByPosition(result).column = new ColumnReplicated(first_column->size(), first_column->replicate(array_column->getOffsets()));
614 615 616
	}
};

617 618 619 620

class FunctionBar : public IFunction
{
public:
621 622 623
	static constexpr auto name = "bar";
	static IFunction * create(const Context & context) { return new FunctionBar; }

624 625 626
	/// Получить имя функции.
	String getName() const
	{
627
		return name;
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
	}

	/// Получить тип результата по типам аргументов. Если функция неприменима для данных аргументов - кинуть исключение.
	DataTypePtr getReturnType(const DataTypes & arguments) const
	{
		if (arguments.size() != 3 && arguments.size() != 4)
			throw Exception("Function " + getName() + " requires from 3 or 4 parameters: value, min_value, max_value, [max_width_of_bar = 80]. Passed "
				+ toString(arguments.size()) + ".",
				ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

		if (!arguments[0]->isNumeric() || !arguments[1]->isNumeric() || !arguments[2]->isNumeric()
			|| (arguments.size() == 4 && !arguments[3]->isNumeric()))
			throw Exception("All arguments for function " + getName() + " must be numeric.", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);

		return new DataTypeString;
	}

	/// Выполнить функцию над блоком.
	void execute(Block & block, const ColumnNumbers & arguments, size_t result)
	{
		Int64 min = extractConstant<Int64>(block, arguments, 1, "Second");	/// Уровень значения, при котором полоска имеет нулевую длину.
		Int64 max = extractConstant<Int64>(block, arguments, 2, "Third");	/// Уровень значения, при котором полоска имеет максимальную длину.

		/// Максимальная ширина полоски в символах, по-умолчанию.
		Float64 max_width = arguments.size() == 4
			? extractConstant<Float64>(block, arguments, 3, "Fourth")
			: 80;

		if (max_width < 1)
			throw Exception("Max_width argument must be >= 1.", ErrorCodes::ARGUMENT_OUT_OF_BOUND);

		if (max_width > 1000)
			throw Exception("Too large max_width.", ErrorCodes::ARGUMENT_OUT_OF_BOUND);

		const auto & src = *block.getByPosition(arguments[0]).column;

		if (src.isConst())
		{
			auto res_column = new ColumnConstString(block.rowsInFirstColumn(), "");
			block.getByPosition(result).column = res_column;

			if (   executeConstNumber<UInt8>	(src, *res_column, min, max, max_width)
				|| executeConstNumber<UInt16>	(src, *res_column, min, max, max_width)
				|| executeConstNumber<UInt32>	(src, *res_column, min, max, max_width)
				|| executeConstNumber<UInt64>	(src, *res_column, min, max, max_width)
				|| executeConstNumber<Int8>		(src, *res_column, min, max, max_width)
				|| executeConstNumber<Int16>	(src, *res_column, min, max, max_width)
				|| executeConstNumber<Int32>	(src, *res_column, min, max, max_width)
				|| executeConstNumber<Int64>	(src, *res_column, min, max, max_width)
				|| executeConstNumber<Float32>	(src, *res_column, min, max, max_width)
				|| executeConstNumber<Float64>	(src, *res_column, min, max, max_width))
			{
			}
			else
				throw Exception("Illegal column " + block.getByPosition(arguments[0]).column->getName()
					+ " of argument of function " + getName(),
					ErrorCodes::ILLEGAL_COLUMN);
		}
		else
		{
			auto res_column = new ColumnString;
			block.getByPosition(result).column = res_column;

			if (   executeNumber<UInt8>		(src, *res_column, min, max, max_width)
				|| executeNumber<UInt16>	(src, *res_column, min, max, max_width)
				|| executeNumber<UInt32>	(src, *res_column, min, max, max_width)
				|| executeNumber<UInt64>	(src, *res_column, min, max, max_width)
				|| executeNumber<Int8>		(src, *res_column, min, max, max_width)
				|| executeNumber<Int16>		(src, *res_column, min, max, max_width)
				|| executeNumber<Int32>		(src, *res_column, min, max, max_width)
				|| executeNumber<Int64>		(src, *res_column, min, max, max_width)
				|| executeNumber<Float32>	(src, *res_column, min, max, max_width)
				|| executeNumber<Float64>	(src, *res_column, min, max, max_width))
			{
			}
			else
				throw Exception("Illegal column " + block.getByPosition(arguments[0]).column->getName()
					+ " of argument of function " + getName(),
					ErrorCodes::ILLEGAL_COLUMN);
		}
	}

private:
	template <typename T>
	T extractConstant(Block & block, const ColumnNumbers & arguments, size_t argument_pos, const char * which_argument) const
	{
		const auto & column = *block.getByPosition(arguments[argument_pos]).column;

		if (!column.isConst())
			throw Exception(which_argument + String(" argument for function ") + getName() + " must be constant.", ErrorCodes::ILLEGAL_COLUMN);

		return apply_visitor(FieldVisitorConvertToNumber<T>(), column[0]);
	}

	template <typename T>
	static void fill(const PODArray<T> & src, ColumnString::Chars_t & dst_chars, ColumnString::Offsets_t & dst_offsets,
		Int64 min, Int64 max, Float64 max_width)
	{
		size_t size = src.size();
		size_t current_offset = 0;

		dst_offsets.resize(size);
730
		dst_chars.reserve(size * (UnicodeBar::getWidthInBytes(max_width) + 1));	/// строки 0-terminated.
731 732 733

		for (size_t i = 0; i < size; ++i)
		{
734 735
			Float64 width = UnicodeBar::getWidth(src[i], min, max, max_width);
			size_t next_size = current_offset + UnicodeBar::getWidthInBytes(width) + 1;
736
			dst_chars.resize(next_size);
737
			UnicodeBar::render(width, reinterpret_cast<char *>(&dst_chars[current_offset]));
738 739 740 741 742 743 744 745 746
			current_offset = next_size;
			dst_offsets[i] = current_offset;
		}
	}

	template <typename T>
	static void fill(T src, String & dst_chars,
		Int64 min, Int64 max, Float64 max_width)
	{
747 748 749
		Float64 width = UnicodeBar::getWidth(src, min, max, max_width);
		dst_chars.resize(UnicodeBar::getWidthInBytes(width));
		UnicodeBar::render(width, &dst_chars[0]);
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
	}

	template <typename T>
	static bool executeNumber(const IColumn & src, ColumnString & dst, Int64 min, Int64 max, Float64 max_width)
	{
		if (const ColumnVector<T> * col = typeid_cast<const ColumnVector<T> *>(&src))
		{
			fill(col->getData(), dst.getChars(), dst.getOffsets(), min, max, max_width);
			return true;
		}
		else
			return false;
	}

	template <typename T>
	static bool executeConstNumber(const IColumn & src, ColumnConstString & dst, Int64 min, Int64 max, Float64 max_width)
	{
		if (const ColumnConst<T> * col = typeid_cast<const ColumnConst<T> *>(&src))
		{
			fill(col->getData(), dst.getData(), min, max, max_width);
			return true;
		}
		else
			return false;
	}
};

777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879

template <typename Impl>
class FunctionNumericPredicate : public IFunction
{
public:
	static constexpr auto name = Impl::name;
	static IFunction * create(const Context &) { return new FunctionNumericPredicate; }

	String getName() const override { return name; }

	DataTypePtr getReturnType(const DataTypes & arguments) const override
	{
		const auto args_size = arguments.size();
		if (args_size != 1)
			throw Exception{
				"Number of arguments for function " + getName() + " doesn't match: passed " +
					toString(args_size) + ", should be 1",
				ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH
			};

		const auto arg = arguments.front().get();
		if (!typeid_cast<const DataTypeUInt8 *>(arg) &&
			!typeid_cast<const DataTypeUInt16 *>(arg) &&
			!typeid_cast<const DataTypeUInt32 *>(arg) &&
			!typeid_cast<const DataTypeUInt64 *>(arg) &&
			!typeid_cast<const DataTypeInt8 *>(arg) &&
			!typeid_cast<const DataTypeInt16 *>(arg) &&
			!typeid_cast<const DataTypeInt32 *>(arg) &&
			!typeid_cast<const DataTypeInt64 *>(arg) &&
			!typeid_cast<const DataTypeFloat32 *>(arg) &&
			!typeid_cast<const DataTypeFloat64 *>(arg))
			throw Exception{
				"Argument for function " + getName() + " must be numeric",
				ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT
			};

		return new DataTypeUInt8;
	}

	void execute(Block & block, const ColumnNumbers & arguments, const size_t result) override
	{
		const auto in = block.getByPosition(arguments.front()).column.get();

		if (!execute<UInt8>(block, in, result) &&
			!execute<UInt16>(block, in, result) &&
			!execute<UInt32>(block, in, result) &&
			!execute<UInt64>(block, in, result) &&
			!execute<Int8>(block, in, result) &&
			!execute<Int16>(block, in, result) &&
			!execute<Int32>(block, in, result) &&
			!execute<Int64>(block, in, result) &&
			!execute<Float32>(block, in, result)  &&
			!execute<Float64>(block, in, result))
			throw Exception{
				"Illegal column " + in->getName() + " of first argument of function " + getName(),
				ErrorCodes::ILLEGAL_COLUMN
			};
	}

	template <typename T>
	bool execute(Block & block, const IColumn * in_untyped, const size_t result) override
	{
		if (const auto in = typeid_cast<const ColumnVector<T> *>(in_untyped))
		{
			const auto size = in->size();

			const auto out = new ColumnVector<UInt8>{size};
			block.getByPosition(result).column = out;

			const auto & in_data = in->getData();
			auto & out_data = out->getData();

			for (const auto i : ext::range(0, size))
				out_data[i] = Impl::execute(in_data[i]);

			return true;
		}
		else if (const auto in = typeid_cast<const ColumnConst<T> *>(in_untyped))
		{
			block.getByPosition(result).column = new ColumnConstUInt8{
				in->size(),
				Impl::execute(in->getData())
			};

			return true;
		}

		return false;
	}
};

struct IsFiniteImpl
{
	static constexpr auto name = "isFinite";
	template <typename T> static bool execute(const T t) { return std::isfinite(t); }
};

struct IsInfiniteImpl
{
	static constexpr auto name = "isInfinite";
	template <typename T> static bool execute(const T t) { return std::isinf(t); }
};

880
struct IsNaNImpl
881
{
882
	static constexpr auto name = "isNaN";
883 884 885 886 887
	template <typename T> static bool execute(const T t) { return std::isnan(t); }
};

using FunctionIsFinite = FunctionNumericPredicate<IsFiniteImpl>;
using FunctionIsInfinite = FunctionNumericPredicate<IsInfiniteImpl>;
888
using FunctionIsNaN = FunctionNumericPredicate<IsNaNImpl>;
889

890

A
Alexey Milovidov 已提交
891
}