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

3 4
#include <Poco/Mutex.h>

A
Alexey Milovidov 已提交
5 6 7 8 9 10
#include <statdaemons/OptimizedRegularExpression.h>

#include <DB/DataTypes/DataTypesNumberFixed.h>
#include <DB/DataTypes/DataTypeString.h>
#include <DB/Columns/ColumnString.h>
#include <DB/Columns/ColumnConst.h>
11
#include <DB/Common/Volnitsky.h>
A
Alexey Milovidov 已提交
12 13 14 15 16 17 18 19 20 21
#include <DB/Functions/IFunction.h>


namespace DB
{

/** Функции поиска и замены в строках:
  *
  * position(haystack, needle)	- обычный поиск подстроки в строке, возвращает позицию (в байтах) найденной подстроки, начиная с 1, или 0, если подстрока не найдена.
  * positionUTF8(haystack, needle) - то же самое, но позиция вычисляется в кодовых точках, при условии, что строка в кодировке UTF-8.
A
Alexey Milovidov 已提交
22 23 24 25
  * 
  * like(haystack, pattern)		- поиск по регулярному выражению LIKE; возвращает 0 или 1. Регистронезависимое, но только для латиницы.
  * notLike(haystack, pattern)
  *
A
Alexey Milovidov 已提交
26
  * match(haystack, pattern)	- поиск по регулярному выражению re2; возвращает 0 или 1.
27
  *
28 29 30 31 32
  * Применяет регексп re2 и достаёт:
  * - первый subpattern, если в regexp-е есть subpattern;
  * - нулевой subpattern (сматчившуюся часть, иначе);
  * - если не сматчилось - пустую строку.
  * extract(haystack, pattern)
A
Alexey Milovidov 已提交
33
  *
A
Alexey Milovidov 已提交
34 35 36
  * replaceOne(haystack, pattern, replacement) - замена шаблона по заданным правилам, только первое вхождение.
  * replaceAll(haystack, pattern, replacement) - замена шаблона по заданным правилам, все вхождения.
  *
37
  * Внимание! На данный момент, аргументы needle, pattern, n, replacement обязаны быть константами.
A
Alexey Milovidov 已提交
38 39 40 41 42
  */


struct PositionImpl
{
A
Alexey Milovidov 已提交
43 44 45
	typedef UInt64 ResultType;

	/// Предполагается, что res нужного размера и инициализирован нулями.
46
	static void vector(const ColumnString::Chars_t & data, const ColumnString::Offsets_t & offsets,
A
Alexey Milovidov 已提交
47
		const std::string & needle,
48
		std::vector<UInt64> & res)
A
Alexey Milovidov 已提交
49 50 51 52 53 54 55 56
	{
		const UInt8 * begin = &data[0];
		const UInt8 * pos = begin;
		const UInt8 * end = pos + data.size();

		/// Текущий индекс в массиве строк.
		size_t i = 0;

57 58
		Volnitsky searcher(needle.data(), needle.size(), end - pos);

A
Alexey Milovidov 已提交
59
		/// Искать будем следующее вхождение сразу во всех строках.
60
		while (pos < end && end != (pos = searcher.search(pos, end - pos)))
A
Alexey Milovidov 已提交
61 62 63 64 65 66 67 68 69
		{
			/// Определим, к какому индексу оно относится.
			while (begin + offsets[i] < pos)
				++i;

			/// Проверяем, что вхождение не переходит через границы строк.
			if (pos + needle.size() < begin + offsets[i])
				res[i] = (i != 0) ? pos - begin - offsets[i - 1] + 1 : (pos - begin + 1);

A
Alexey Milovidov 已提交
70
			pos = begin + offsets[i];
A
Alexey Milovidov 已提交
71 72
			++i;
		}
A
Alexey Milovidov 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
	}

	static void constant(const std::string & data, const std::string & needle, UInt64 & res)
	{
		res = data.find(needle);
		if (res == std::string::npos)
			res = 0;
		else
			++res;
	}
};


struct PositionUTF8Impl
{
	typedef UInt64 ResultType;
	
90
	static void vector(const ColumnString::Chars_t & data, const ColumnString::Offsets_t & offsets,
A
Alexey Milovidov 已提交
91
		const std::string & needle,
92
		std::vector<UInt64> & res)
A
Alexey Milovidov 已提交
93 94 95 96
	{
		const UInt8 * begin = &data[0];
		const UInt8 * pos = begin;
		const UInt8 * end = pos + data.size();
A
Alexey Milovidov 已提交
97

A
Alexey Milovidov 已提交
98 99 100
		/// Текущий индекс в массиве строк.
		size_t i = 0;

101 102
		Volnitsky searcher(needle.data(), needle.size(), end - pos);

A
Alexey Milovidov 已提交
103
		/// Искать будем следующее вхождение сразу во всех строках.
104
		while (pos < end && end != (pos = searcher.search(pos, end - pos)))
A
Alexey Milovidov 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
		{
			/// Определим, к какому индексу оно относится.
			while (begin + offsets[i] < pos)
				++i;

			/// Проверяем, что вхождение не переходит через границы строк.
			if (pos + needle.size() < begin + offsets[i])
			{
				/// А теперь надо найти, сколько кодовых точек находится перед pos.
				res[i] = 1;
				for (const UInt8 * c = begin + (i != 0 ? offsets[i - 1] : 0); c < pos; ++c)
					if (*c <= 0x7F || *c >= 0xC0)
						++res[i];
			}

			pos = begin + offsets[i];
			++i;
		}
A
Alexey Milovidov 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135
	}

	static void constant(const std::string & data, const std::string & needle, UInt64 & res)
	{
		res = data.find(needle);
		if (res == std::string::npos)
			res = 0;
		else
			++res;
	}
};


A
Alexey Milovidov 已提交
136
/// Переводит выражение LIKE в regexp re2. Например, abc%def -> ^abc.*def$
A
Alexey Milovidov 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
inline String likePatternToRegexp(const String & pattern)
{
	String res = "^";
	res.reserve(pattern.size() * 2);
	const char * pos = pattern.data();
	const char * end = pos + pattern.size();

	while (pos < end)
	{
		switch (*pos)
		{
			case '^': case '$': case '.': case '[': case '|': case '(': case ')': case '?': case '*': case '+': case '{':
				res += '\\';
				res += *pos;
				break;
			case '%':
				res += ".*";
				break;
			case '_':
				res += ".";
				break;
			case '\\':
				++pos;
				if (pos == end)
					res += "\\\\";
				else
				{
					if (*pos == '%' || *pos == '_')
						res += *pos;
					else
					{
						res += '\\';
						res += *pos;
					}
				}
				break;
			default:
				res += *pos;
				break;
		}
		++pos;
	}

	res += '$';
	return res;
}


A
Alexey Milovidov 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
/// Сводится ли выражение LIKE к поиску подстроки в строке?
inline bool likePatternIsStrstr(const String & pattern, String & res)
{
	res = "";

	if (pattern.size() < 2 || *pattern.begin() != '%' || *pattern.rbegin() != '%')
		return false;

	res.reserve(pattern.size() * 2);

	const char * pos = pattern.data();
	const char * end = pos + pattern.size();

	++pos;
	--end;

	while (pos < end)
	{
		switch (*pos)
		{
			case '%': case '_':
				return false;
			case '\\':
				++pos;
				if (pos == end)
					return false;
				else
					res += *pos;
				break;
			default:
				res += *pos;
				break;
		}
		++pos;
	}

	return true;
}


A
Alexey Milovidov 已提交
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
struct Regexps
{
	typedef std::map<String, OptimizedRegularExpression> KnownRegexps;

	static const OptimizedRegularExpression & get(const std::string & pattern)
	{
		/// В GCC thread safe statics.
		static KnownRegexps known_regexps;
		static Poco::FastMutex mutex;
		Poco::ScopedLock<Poco::FastMutex> lock(mutex);

		KnownRegexps::const_iterator it = known_regexps.find(pattern);
		if (known_regexps.end() == it)
			it = known_regexps.insert(std::make_pair(pattern, OptimizedRegularExpression(pattern))).first;

		return it->second;
	}

	static const OptimizedRegularExpression & getLike(const std::string & pattern)
	{
		/// В GCC thread safe statics.
		static KnownRegexps known_regexps;
		static Poco::FastMutex mutex;
		Poco::ScopedLock<Poco::FastMutex> lock(mutex);

		KnownRegexps::const_iterator it = known_regexps.find(pattern);
		if (known_regexps.end() == it)
A
Alexey Milovidov 已提交
252
 			it = known_regexps.insert(std::make_pair(pattern, OptimizedRegularExpression(likePatternToRegexp(pattern)))).first;
A
Alexey Milovidov 已提交
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268

		return it->second;
	}
};


/** like - использовать выражения LIKE, если true; использовать выражения re2, если false.
  * Замечание: хотелось бы запускать регексп сразу над всем массивом, аналогично функции position,
  *  но для этого пришлось бы сделать поддержку символов \0 в движке регулярных выражений,
  *  и их интерпретацию как начал и концов строк.
  */
template <bool like, bool revert = false>
struct MatchImpl
{
	typedef UInt8 ResultType;

269
	static void vector(const ColumnString::Chars_t & data, const ColumnString::Offsets_t & offsets,
A
Alexey Milovidov 已提交
270
		const std::string & pattern,
271
		std::vector<UInt8> & res)
A
Alexey Milovidov 已提交
272
	{
A
Alexey Milovidov 已提交
273 274 275 276
		String strstr_pattern;
		/// Простой случай, когда выражение LIKE сводится к поиску подстроки в строке
		if (like && likePatternIsStrstr(pattern, strstr_pattern))
		{
277 278 279 280
			/// Если отрицание - то заполним вектор единицами (вместо имеющихся там нулей)
			if (revert)
				memset(&res[0], 1, offsets.size());
			
A
Alexey Milovidov 已提交
281 282 283 284 285 286
			const UInt8 * begin = &data[0];
			const UInt8 * pos = begin;
			const UInt8 * end = pos + data.size();

			/// Текущий индекс в массиве строк.
			size_t i = 0;
A
Alexey Milovidov 已提交
287

288 289
			Volnitsky searcher(strstr_pattern.data(), strstr_pattern.size(), end - pos);

A
Alexey Milovidov 已提交
290
			/// Искать будем следующее вхождение сразу во всех строках.
291
			while (pos < end && end != (pos = searcher.search(pos, end - pos)))
A
Alexey Milovidov 已提交
292 293 294 295 296 297 298
			{
				/// Определим, к какому индексу оно относится.
				while (begin + offsets[i] < pos)
					++i;

				/// Проверяем, что вхождение не переходит через границы строк.
				if (pos + strstr_pattern.size() < begin + offsets[i])
299
					res[i] = !revert;
A
Alexey Milovidov 已提交
300 301 302 303 304 305 306 307 308 309 310

				pos = begin + offsets[i];
				++i;
			}
		}
		else
		{
			const OptimizedRegularExpression & regexp = like ? Regexps::getLike(pattern) : Regexps::get(pattern);

			size_t size = offsets.size();
			for (size_t i = 0; i < size; ++i)
311
				res[i] = revert ^ regexp.match(reinterpret_cast<const char *>(&data[i != 0 ? offsets[i - 1] : 0]), (i != 0 ? offsets[i] - offsets[i - 1] : offsets[0]) - 1);
A
Alexey Milovidov 已提交
312
		}
A
Alexey Milovidov 已提交
313 314 315 316 317 318 319 320 321 322
	}

	static void constant(const std::string & data, const std::string & pattern, UInt8 & res)
	{
		const OptimizedRegularExpression & regexp = like ? Regexps::getLike(pattern) : Regexps::get(pattern);
		res = revert ^ regexp.match(data);
	}
};


323 324
struct ExtractImpl
{
325
	static void vector(const ColumnString::Chars_t & data, const ColumnString::Offsets_t & offsets,
326
					   const std::string & pattern,
327
					   ColumnString::Chars_t & res_data, ColumnString::Offsets_t & res_offsets)
328
	{
329
		res_data.reserve(data.size() / 5);
330 331 332 333
		res_offsets.resize(offsets.size());
		
		const OptimizedRegularExpression & regexp = Regexps::get(pattern);

334
		unsigned capture = regexp.getNumberOfSubpatterns() > 0 ? 1 : 0;
335 336 337 338 339 340 341 342 343
		OptimizedRegularExpression::MatchVec matches;
		matches.reserve(capture + 1);
		size_t prev_offset = 0;
		size_t res_offset = 0;

		for (size_t i = 0; i < offsets.size(); ++i)
		{
			size_t cur_offset = offsets[i];
			
344 345
			unsigned count = regexp.match(reinterpret_cast<const char *>(&data[prev_offset]), cur_offset - prev_offset - 1, matches, capture + 1);
			if (count > capture && matches[capture].offset != std::string::npos)
346
			{
347
				const OptimizedRegularExpression::Match & match = matches[capture];
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
				res_data.resize(res_offset + match.length + 1);
				memcpy(&res_data[res_offset], &data[prev_offset + match.offset], match.length);
				res_offset += match.length;
			}
			else
			{
				res_data.resize(res_offset + 1);
			}
			
			res_data[res_offset] = 0;
			++res_offset;
			res_offsets[i] = res_offset;

			prev_offset = cur_offset;
		}
	}
};


A
Alexey Milovidov 已提交
367 368
template <typename Impl, typename Name>
class FunctionsStringSearch : public IFunction
A
Alexey Milovidov 已提交
369 370 371 372 373
{
public:
	/// Получить имя функции.
	String getName() const
	{
A
Alexey Milovidov 已提交
374
		return Name::get();
A
Alexey Milovidov 已提交
375 376 377 378 379 380 381
	}

	/// Получить тип результата по типам аргументов. Если функция неприменима для данных аргументов - кинуть исключение.
	DataTypePtr getReturnType(const DataTypes & arguments) const
	{
		if (arguments.size() != 2)
			throw Exception("Number of arguments for function " + getName() + " doesn't match: passed "
382
				+ toString(arguments.size()) + ", should be 2.",
A
Alexey Milovidov 已提交
383 384 385 386 387 388 389 390 391 392
				ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

		if (!dynamic_cast<const DataTypeString *>(&*arguments[0]))
			throw Exception("Illegal type " + arguments[0]->getName() + " of argument of function " + getName(),
				ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);

		if (!dynamic_cast<const DataTypeString *>(&*arguments[1]))
			throw Exception("Illegal type " + arguments[1]->getName() + " of argument of function " + getName(),
				ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);

A
Alexey Milovidov 已提交
393
		return new typename DataTypeFromFieldType<typename Impl::ResultType>::Type;
A
Alexey Milovidov 已提交
394 395 396 397 398
	}

	/// Выполнить функцию над блоком.
	void execute(Block & block, const ColumnNumbers & arguments, size_t result)
	{
A
Alexey Milovidov 已提交
399
		typedef typename Impl::ResultType ResultType;
A
Alexey Milovidov 已提交
400 401 402 403 404 405 406 407 408 409 410 411 412
		
		const ColumnPtr column = block.getByPosition(arguments[0]).column;
		const ColumnPtr column_needle = block.getByPosition(arguments[1]).column;

		const ColumnConstString * col_needle = dynamic_cast<const ColumnConstString *>(&*column_needle);
		if (!col_needle)
			throw Exception("Second argument of function " + getName() + " must be constant string.", ErrorCodes::ILLEGAL_COLUMN);
		
		if (const ColumnString * col = dynamic_cast<const ColumnString *>(&*column))
		{
			ColumnVector<ResultType> * col_res = new ColumnVector<ResultType>;
			block.getByPosition(result).column = col_res;

A
Alexey Milovidov 已提交
413
			typename ColumnVector<ResultType>::Container_t & vec_res = col_res->getData();
A
Alexey Milovidov 已提交
414
			vec_res.resize(col->size());
415
			Impl::vector(col->getChars(), col->getOffsets(), col_needle->getData(), vec_res);
A
Alexey Milovidov 已提交
416 417 418 419
		}
		else if (const ColumnConstString * col = dynamic_cast<const ColumnConstString *>(&*column))
		{
			ResultType res = 0;
A
Alexey Milovidov 已提交
420
			Impl::constant(col->getData(), col_needle->getData(), res);
A
Alexey Milovidov 已提交
421 422 423 424 425 426 427 428 429 430 431

			ColumnConst<ResultType> * col_res = new ColumnConst<ResultType>(col->size(), res);
			block.getByPosition(result).column = col_res;
		}
		else
		   throw Exception("Illegal column " + block.getByPosition(arguments[0]).column->getName()
				+ " of argument of function " + getName(),
				ErrorCodes::ILLEGAL_COLUMN);
	}
};

A
Alexey Milovidov 已提交
432

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
template <typename Impl, typename Name>
class FunctionsStringSearchToString : public IFunction
{
public:
	/// Получить имя функции.
	String getName() const
	{
		return Name::get();
	}
	
	/// Получить тип результата по типам аргументов. Если функция неприменима для данных аргументов - кинуть исключение.
	DataTypePtr getReturnType(const DataTypes & arguments) const
	{
		if (arguments.size() != 2)
			throw Exception("Number of arguments for function " + getName() + " doesn't match: passed "
448
			+ toString(arguments.size()) + ", should be 2.",
449
							ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);
450 451 452 453 454 455 456 457 458 459
		
		if (!dynamic_cast<const DataTypeString *>(&*arguments[0]))
			throw Exception("Illegal type " + arguments[0]->getName() + " of argument of function " + getName(),
			ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);
		
		if (!dynamic_cast<const DataTypeString *>(&*arguments[1]))
			throw Exception("Illegal type " + arguments[1]->getName() + " of argument of function " + getName(),
			ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);
		
		return new DataTypeString;
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
	}
	
	/// Выполнить функцию над блоком.
	void execute(Block & block, const ColumnNumbers & arguments, size_t result)
	{
		const ColumnPtr column = block.getByPosition(arguments[0]).column;
		const ColumnPtr column_needle = block.getByPosition(arguments[1]).column;
		
		const ColumnConstString * col_needle = dynamic_cast<const ColumnConstString *>(&*column_needle);
		if (!col_needle)
			throw Exception("Second argument of function " + getName() + " must be constant string.", ErrorCodes::ILLEGAL_COLUMN);
		
		if (const ColumnString * col = dynamic_cast<const ColumnString *>(&*column))
		{
			ColumnString * col_res = new ColumnString;
			block.getByPosition(result).column = col_res;
			
477
			ColumnString::Chars_t & vec_res = col_res->getChars();
478
			ColumnString::Offsets_t & offsets_res = col_res->getOffsets();
479
			Impl::vector(col->getChars(), col->getOffsets(), col_needle->getData(), vec_res, offsets_res);
480 481 482
		}
		else if (const ColumnConstString * col = dynamic_cast<const ColumnConstString *>(&*column))
		{
483
			const std::string & data = col->getData();
484 485 486
			ColumnString::Chars_t vdata(
				reinterpret_cast<const ColumnString::Chars_t::value_type *>(data.c_str()),
				reinterpret_cast<const ColumnString::Chars_t::value_type *>(data.c_str() + data.size() + 1));
487
			ColumnString::Offsets_t offsets(1, vdata.size());
488
			ColumnString::Chars_t res_vdata;
489
			ColumnString::Offsets_t res_offsets;
490 491
			Impl::vector(vdata, offsets, col_needle->getData(), res_vdata, res_offsets);
			
492 493 494 495
			std::string res;

			if (!res_offsets.empty())
				res.assign(&res_vdata[0], &res_vdata[res_vdata.size() - 1]);
496 497 498 499 500 501 502 503 504 505 506 507
			
			ColumnConstString * col_res = new ColumnConstString(col->size(), res);
			block.getByPosition(result).column = col_res;
		}
		else
			throw Exception("Illegal column " + block.getByPosition(arguments[0]).column->getName()
			+ " of argument of function " + getName(),
							ErrorCodes::ILLEGAL_COLUMN);
	}
};


A
Alexey Milovidov 已提交
508 509 510 511 512
struct NamePosition 		{ static const char * get() { return "position"; } };
struct NamePositionUTF8		{ static const char * get() { return "positionUTF8"; } };
struct NameMatch			{ static const char * get() { return "match"; } };
struct NameLike				{ static const char * get() { return "like"; } };
struct NameNotLike			{ static const char * get() { return "notLike"; } };
513
struct NameExtract			{ static const char * get() { return "extract"; } };
A
Alexey Milovidov 已提交
514 515 516 517

typedef FunctionsStringSearch<PositionImpl, 			NamePosition> 		FunctionPosition;
typedef FunctionsStringSearch<PositionUTF8Impl, 		NamePositionUTF8> 	FunctionPositionUTF8;
typedef FunctionsStringSearch<MatchImpl<false>, 		NameMatch> 			FunctionMatch;
518
typedef FunctionsStringSearch<MatchImpl<true>, 			NameLike> 			FunctionLike;
A
Alexey Milovidov 已提交
519
typedef FunctionsStringSearch<MatchImpl<true, true>, 	NameNotLike> 		FunctionNotLike;
520
typedef FunctionsStringSearchToString<ExtractImpl, 		NameExtract> 		FunctionExtract;
A
Alexey Milovidov 已提交
521

A
Alexey Milovidov 已提交
522
}