zclllyybb commented on code in PR #58957:
URL: https://github.com/apache/doris/pull/58957#discussion_r2616188446
##########
be/src/vec/functions/function_string.h:
##########
@@ -5261,146 +5258,132 @@ class FunctionCrc32Internal : public IFunction {
}
};
-class FunctionUnicodeNormalize : public IFunction {
+class FunctionStringLevenshtein : public IFunction {
public:
- static constexpr auto name = "unicode_normalize";
-
- static FunctionPtr create() { return
std::make_shared<FunctionUnicodeNormalize>(); }
-
+ static constexpr auto name = "levenshtein";
+ static FunctionPtr create() { return
std::make_shared<FunctionStringLevenshtein>(); }
String get_name() const override { return name; }
-
size_t get_number_of_arguments() const override { return 2; }
-
DataTypePtr get_return_type_impl(const DataTypes& arguments) const
override {
- if (arguments.size() != 2 ||
!is_string_type(arguments[0]->get_primitive_type()) ||
- !is_string_type(arguments[1]->get_primitive_type())) {
- throw doris::Exception(ErrorCode::INVALID_ARGUMENT,
- "Illegal type {} and {} of arguments of
function {}",
- arguments[0]->get_name(),
arguments[1]->get_name(), get_name());
- }
- return arguments[0];
+ return std::make_shared<DataTypeInt32>();
}
+ bool use_default_implementation_for_nulls() const override { return true; }
- ColumnNumbers get_arguments_that_are_always_constant() const override {
return {1}; }
+ Status execute_impl(FunctionContext* context, Block& block, const
ColumnNumbers& arguments,
+ uint32_t result, size_t input_rows_count) const
override {
+ // Convert input columns to full columns
+ auto col_left =
+
block.get_by_position(arguments[0]).column->convert_to_full_column_if_const();
+ auto col_right =
+
block.get_by_position(arguments[1]).column->convert_to_full_column_if_const();
- Status open(FunctionContext* context, FunctionContext::FunctionStateScope
scope) override {
- if (scope == FunctionContext::THREAD_LOCAL) {
- return Status::OK();
- }
+ const auto* col_left_str =
check_and_get_column<ColumnString>(col_left.get());
+ const auto* col_right_str =
check_and_get_column<ColumnString>(col_right.get());
- if (!context->is_col_constant(1)) {
- return Status::InvalidArgument(
- "The second argument 'mode' of function {} must be
constant", get_name());
- }
-
- auto* const_col = context->get_constant_col(1);
- auto mode_ref = const_col->column_ptr->get_data_at(0);
- std::string lower_mode =
doris::to_lower(std::string(doris::trim(mode_ref.to_string())));
-
- UErrorCode status = U_ZERO_ERROR;
- const icu::Normalizer2* normalizer = nullptr;
-
- if (lower_mode == "nfc") {
- normalizer = icu::Normalizer2::getInstance(nullptr, "nfc",
UNORM2_COMPOSE, status);
- } else if (lower_mode == "nfd") {
- normalizer = icu::Normalizer2::getNFDInstance(status);
- } else if (lower_mode == "nfkc") {
- normalizer = icu::Normalizer2::getInstance(nullptr, "nfkc",
UNORM2_COMPOSE, status);
- } else if (lower_mode == "nfkd") {
- normalizer = icu::Normalizer2::getNFKDInstance(status);
- } else if (lower_mode == "nfkc_cf") {
- normalizer = icu::Normalizer2::getInstance(nullptr, "nfkc_cf",
UNORM2_COMPOSE, status);
- } else {
- return Status::InvalidArgument(
- "Invalid normalization mode '{}' for function {}. "
- "Supported modes: NFC, NFD, NFKC, NFKD, NFKC_CF",
- lower_mode, get_name());
+ if (!col_left_str || !col_right_str) {
+ return Status::InternalError("Levenshtein arguments must be
String");
}
- if (U_FAILURE(status) || normalizer == nullptr) {
- return Status::InvalidArgument(
- "Failed to get normalizer instance for mode '{}' in
function {}: {}",
- lower_mode, get_name(), u_errorName(status));
- }
+ auto col_res = ColumnInt32::create(input_rows_count);
+ auto& res_data = col_res->get_data();
- auto state = std::make_shared<UnicodeNormalizeState>();
- state->normalizer = normalizer;
- context->set_function_state(scope, state);
+ vector_vector(col_left_str, col_right_str, res_data, input_rows_count);
+
+ block.replace_by_position(result, std::move(col_res));
return Status::OK();
}
- Status execute_impl(FunctionContext* context, Block& block, const
ColumnNumbers& arguments,
- uint32_t result, size_t input_rows_count) const
override {
- auto* state = reinterpret_cast<UnicodeNormalizeState*>(
- context->get_function_state(FunctionContext::FRAGMENT_LOCAL));
- if (state == nullptr || state->normalizer == nullptr) {
- return Status::RuntimeError("unicode_normalize function state is
not initialized");
- }
-
- ColumnPtr col =
-
block.get_by_position(arguments[0]).column->convert_to_full_column_if_const();
- const auto* col_str = check_and_get_column<ColumnString>(col.get());
- if (col_str == nullptr) {
- return Status::RuntimeError("Illegal column {} of argument of
function {}",
-
block.get_by_position(arguments[0]).column->get_name(),
- get_name());
- }
+private:
+ // Helper: Convert UTF-8 bytes to Unicode code points
+ static void to_utf8_codepoints(const StringRef& str,
std::vector<uint32_t>& result) {
+ result.clear();
+ const char* p = str.data;
+ const char* end = str.data + str.size;
+
+ while (p < end) {
+ unsigned char c = static_cast<unsigned char>(*p);
+ uint32_t code_point = 0;
+ int bytes = 0;
+
+ if (c < 0x80) { // 1-byte sequence (ASCII)
+ bytes = 1;
+ code_point = c;
+ } else if ((c & 0xE0) == 0xC0) { // 2-byte sequence
+ bytes = 2;
+ code_point = c & 0x1F;
+ } else if ((c & 0xF0) == 0xE0) { // 3-byte sequence (Chinese, etc.)
+ bytes = 3;
+ code_point = c & 0x0F;
+ } else if ((c & 0xF8) == 0xF0) { // 4-byte sequence
+ bytes = 4;
+ code_point = c & 0x07;
+ } else {
+ // Invalid UTF-8, skip 1 byte
+ p++;
+ continue;
+ }
- const auto& data = col_str->get_chars();
- const auto& offsets = col_str->get_offsets();
+ // Boundary check
+ if (p + bytes > end) break;
- auto res = ColumnString::create();
- auto& res_data = res->get_chars();
- auto& res_offsets = res->get_offsets();
+ // Combine remaining bytes
+ for (int i = 1; i < bytes; ++i) {
+ code_point = (code_point << 6) | (p[i] & 0x3F);
+ }
+ result.push_back(code_point);
+ p += bytes;
+ }
+ }
- size_t rows = offsets.size();
- res_offsets.resize(rows);
+ static int32_t calculate_levenshtein(const StringRef& str1, const
StringRef& str2) {
+ // Parse UTF-8 strings to code points
+ std::vector<uint32_t> source, target;
+ to_utf8_codepoints(str1, source);
+ to_utf8_codepoints(str2, target);
- std::string tmp;
- for (size_t i = 0; i < rows; ++i) {
- const char* begin = reinterpret_cast<const char*>(&data[offsets[i
- 1]]);
- size_t len = offsets[i] - offsets[i - 1];
+ const size_t len1 = source.size();
+ const size_t len2 = target.size();
- normalize_one(state->normalizer, begin, len, tmp);
- StringOP::push_value_string(tmp, i, res_data, res_offsets);
- }
+ // Edge cases for empty strings
+ if (len1 == 0) return static_cast<int32_t>(len2);
+ if (len2 == 0) return static_cast<int32_t>(len1);
- block.replace_by_position(result, std::move(res));
- return Status::OK();
- }
+ // DP vectors
+ std::vector<int32_t> prev_dp(len2 + 1);
+ std::vector<int32_t> curr_dp(len2 + 1);
-private:
- struct UnicodeNormalizeState {
- const icu::Normalizer2* normalizer = nullptr;
- };
+ // Initialize first row
+ for (size_t j = 0; j <= len2; ++j) prev_dp[j] =
static_cast<int32_t>(j);
- static void normalize_one(const icu::Normalizer2* normalizer, const char*
input, size_t length,
- std::string& output) {
- if (length == 0) {
- output.clear();
- return;
+ // DP Calculation
+ for (size_t i = 1; i <= len1; ++i) {
+ curr_dp[0] = static_cast<int32_t>(i);
+ for (size_t j = 1; j <= len2; ++j) {
+ // Compare code points instead of bytes
+ int cost = (source[i - 1] == target[j - 1]) ? 0 : 1;
+ curr_dp[j] = std::min({prev_dp[j] + 1, // Deletion
+ curr_dp[j - 1] + 1, // Insertion
+ prev_dp[j - 1] + cost}); // Substitution
+ }
+ prev_dp.swap(curr_dp);
}
+ return prev_dp[len2];
+ }
- icu::StringPiece sp(input, static_cast<int32_t>(length));
- icu::UnicodeString src16 = icu::UnicodeString::fromUTF8(sp);
-
- UErrorCode status = U_ZERO_ERROR;
- UNormalizationCheckResult quick = normalizer->quickCheck(src16,
status);
- if (U_SUCCESS(status) && quick == UNORM_YES) {
- output.assign(input, length);
- return;
- }
+ static void vector_vector(const ColumnString* col_left, const
ColumnString* col_right,
+ PaddedPODArray<Int32>& res, size_t rows) {
+ const auto& l_offsets = col_left->get_offsets();
+ const auto& l_chars = col_left->get_chars();
+ const auto& r_offsets = col_right->get_offsets();
+ const auto& r_chars = col_right->get_chars();
- icu::UnicodeString result16;
- status = U_ZERO_ERROR;
- normalizer->normalize(src16, result16, status);
- if (U_FAILURE(status)) {
- output.assign(input, length);
- return;
+ for (size_t i = 0; i < rows; ++i) {
+ auto l_off = i == 0 ? 0 : l_offsets[i - 1];
+ auto r_off = i == 0 ? 0 : r_offsets[i - 1];
+ StringRef lstr(reinterpret_cast<const char*>(&l_chars[l_off]),
l_offsets[i] - l_off);
Review Comment:
prefer not to use `reinterpret_cast`
##########
be/src/vec/functions/function_string.h:
##########
@@ -5261,146 +5258,132 @@ class FunctionCrc32Internal : public IFunction {
}
};
-class FunctionUnicodeNormalize : public IFunction {
+class FunctionStringLevenshtein : public IFunction {
public:
- static constexpr auto name = "unicode_normalize";
-
- static FunctionPtr create() { return
std::make_shared<FunctionUnicodeNormalize>(); }
-
+ static constexpr auto name = "levenshtein";
+ static FunctionPtr create() { return
std::make_shared<FunctionStringLevenshtein>(); }
String get_name() const override { return name; }
-
size_t get_number_of_arguments() const override { return 2; }
-
DataTypePtr get_return_type_impl(const DataTypes& arguments) const
override {
- if (arguments.size() != 2 ||
!is_string_type(arguments[0]->get_primitive_type()) ||
- !is_string_type(arguments[1]->get_primitive_type())) {
- throw doris::Exception(ErrorCode::INVALID_ARGUMENT,
- "Illegal type {} and {} of arguments of
function {}",
- arguments[0]->get_name(),
arguments[1]->get_name(), get_name());
- }
- return arguments[0];
+ return std::make_shared<DataTypeInt32>();
}
+ bool use_default_implementation_for_nulls() const override { return true; }
- ColumnNumbers get_arguments_that_are_always_constant() const override {
return {1}; }
+ Status execute_impl(FunctionContext* context, Block& block, const
ColumnNumbers& arguments,
+ uint32_t result, size_t input_rows_count) const
override {
+ // Convert input columns to full columns
+ auto col_left =
+
block.get_by_position(arguments[0]).column->convert_to_full_column_if_const();
+ auto col_right =
+
block.get_by_position(arguments[1]).column->convert_to_full_column_if_const();
- Status open(FunctionContext* context, FunctionContext::FunctionStateScope
scope) override {
- if (scope == FunctionContext::THREAD_LOCAL) {
- return Status::OK();
- }
+ const auto* col_left_str =
check_and_get_column<ColumnString>(col_left.get());
+ const auto* col_right_str =
check_and_get_column<ColumnString>(col_right.get());
- if (!context->is_col_constant(1)) {
- return Status::InvalidArgument(
- "The second argument 'mode' of function {} must be
constant", get_name());
- }
-
- auto* const_col = context->get_constant_col(1);
- auto mode_ref = const_col->column_ptr->get_data_at(0);
- std::string lower_mode =
doris::to_lower(std::string(doris::trim(mode_ref.to_string())));
-
- UErrorCode status = U_ZERO_ERROR;
- const icu::Normalizer2* normalizer = nullptr;
-
- if (lower_mode == "nfc") {
- normalizer = icu::Normalizer2::getInstance(nullptr, "nfc",
UNORM2_COMPOSE, status);
- } else if (lower_mode == "nfd") {
- normalizer = icu::Normalizer2::getNFDInstance(status);
- } else if (lower_mode == "nfkc") {
- normalizer = icu::Normalizer2::getInstance(nullptr, "nfkc",
UNORM2_COMPOSE, status);
- } else if (lower_mode == "nfkd") {
- normalizer = icu::Normalizer2::getNFKDInstance(status);
- } else if (lower_mode == "nfkc_cf") {
- normalizer = icu::Normalizer2::getInstance(nullptr, "nfkc_cf",
UNORM2_COMPOSE, status);
- } else {
- return Status::InvalidArgument(
- "Invalid normalization mode '{}' for function {}. "
- "Supported modes: NFC, NFD, NFKC, NFKD, NFKC_CF",
- lower_mode, get_name());
+ if (!col_left_str || !col_right_str) {
+ return Status::InternalError("Levenshtein arguments must be
String");
}
- if (U_FAILURE(status) || normalizer == nullptr) {
- return Status::InvalidArgument(
- "Failed to get normalizer instance for mode '{}' in
function {}: {}",
- lower_mode, get_name(), u_errorName(status));
- }
+ auto col_res = ColumnInt32::create(input_rows_count);
+ auto& res_data = col_res->get_data();
- auto state = std::make_shared<UnicodeNormalizeState>();
- state->normalizer = normalizer;
- context->set_function_state(scope, state);
+ vector_vector(col_left_str, col_right_str, res_data, input_rows_count);
+
+ block.replace_by_position(result, std::move(col_res));
return Status::OK();
}
- Status execute_impl(FunctionContext* context, Block& block, const
ColumnNumbers& arguments,
- uint32_t result, size_t input_rows_count) const
override {
- auto* state = reinterpret_cast<UnicodeNormalizeState*>(
- context->get_function_state(FunctionContext::FRAGMENT_LOCAL));
- if (state == nullptr || state->normalizer == nullptr) {
- return Status::RuntimeError("unicode_normalize function state is
not initialized");
- }
-
- ColumnPtr col =
-
block.get_by_position(arguments[0]).column->convert_to_full_column_if_const();
- const auto* col_str = check_and_get_column<ColumnString>(col.get());
- if (col_str == nullptr) {
- return Status::RuntimeError("Illegal column {} of argument of
function {}",
-
block.get_by_position(arguments[0]).column->get_name(),
- get_name());
- }
+private:
+ // Helper: Convert UTF-8 bytes to Unicode code points
+ static void to_utf8_codepoints(const StringRef& str,
std::vector<uint32_t>& result) {
+ result.clear();
+ const char* p = str.data;
+ const char* end = str.data + str.size;
+
+ while (p < end) {
+ unsigned char c = static_cast<unsigned char>(*p);
+ uint32_t code_point = 0;
+ int bytes = 0;
+
+ if (c < 0x80) { // 1-byte sequence (ASCII)
Review Comment:
we already have a way to deal with utf8, could reference `SubReplaceImpl`
##########
be/src/vec/functions/function_string.h:
##########
@@ -5261,146 +5258,132 @@ class FunctionCrc32Internal : public IFunction {
}
};
-class FunctionUnicodeNormalize : public IFunction {
+class FunctionStringLevenshtein : public IFunction {
public:
- static constexpr auto name = "unicode_normalize";
-
- static FunctionPtr create() { return
std::make_shared<FunctionUnicodeNormalize>(); }
-
+ static constexpr auto name = "levenshtein";
+ static FunctionPtr create() { return
std::make_shared<FunctionStringLevenshtein>(); }
String get_name() const override { return name; }
-
size_t get_number_of_arguments() const override { return 2; }
-
DataTypePtr get_return_type_impl(const DataTypes& arguments) const
override {
- if (arguments.size() != 2 ||
!is_string_type(arguments[0]->get_primitive_type()) ||
- !is_string_type(arguments[1]->get_primitive_type())) {
- throw doris::Exception(ErrorCode::INVALID_ARGUMENT,
- "Illegal type {} and {} of arguments of
function {}",
- arguments[0]->get_name(),
arguments[1]->get_name(), get_name());
- }
- return arguments[0];
+ return std::make_shared<DataTypeInt32>();
}
+ bool use_default_implementation_for_nulls() const override { return true; }
- ColumnNumbers get_arguments_that_are_always_constant() const override {
return {1}; }
+ Status execute_impl(FunctionContext* context, Block& block, const
ColumnNumbers& arguments,
+ uint32_t result, size_t input_rows_count) const
override {
+ // Convert input columns to full columns
+ auto col_left =
+
block.get_by_position(arguments[0]).column->convert_to_full_column_if_const();
+ auto col_right =
+
block.get_by_position(arguments[1]).column->convert_to_full_column_if_const();
- Status open(FunctionContext* context, FunctionContext::FunctionStateScope
scope) override {
- if (scope == FunctionContext::THREAD_LOCAL) {
- return Status::OK();
- }
+ const auto* col_left_str =
check_and_get_column<ColumnString>(col_left.get());
+ const auto* col_right_str =
check_and_get_column<ColumnString>(col_right.get());
- if (!context->is_col_constant(1)) {
- return Status::InvalidArgument(
- "The second argument 'mode' of function {} must be
constant", get_name());
- }
-
- auto* const_col = context->get_constant_col(1);
- auto mode_ref = const_col->column_ptr->get_data_at(0);
- std::string lower_mode =
doris::to_lower(std::string(doris::trim(mode_ref.to_string())));
-
- UErrorCode status = U_ZERO_ERROR;
- const icu::Normalizer2* normalizer = nullptr;
-
- if (lower_mode == "nfc") {
- normalizer = icu::Normalizer2::getInstance(nullptr, "nfc",
UNORM2_COMPOSE, status);
- } else if (lower_mode == "nfd") {
- normalizer = icu::Normalizer2::getNFDInstance(status);
- } else if (lower_mode == "nfkc") {
- normalizer = icu::Normalizer2::getInstance(nullptr, "nfkc",
UNORM2_COMPOSE, status);
- } else if (lower_mode == "nfkd") {
- normalizer = icu::Normalizer2::getNFKDInstance(status);
- } else if (lower_mode == "nfkc_cf") {
- normalizer = icu::Normalizer2::getInstance(nullptr, "nfkc_cf",
UNORM2_COMPOSE, status);
- } else {
- return Status::InvalidArgument(
- "Invalid normalization mode '{}' for function {}. "
- "Supported modes: NFC, NFD, NFKC, NFKD, NFKC_CF",
- lower_mode, get_name());
+ if (!col_left_str || !col_right_str) {
+ return Status::InternalError("Levenshtein arguments must be
String");
}
- if (U_FAILURE(status) || normalizer == nullptr) {
- return Status::InvalidArgument(
- "Failed to get normalizer instance for mode '{}' in
function {}: {}",
- lower_mode, get_name(), u_errorName(status));
- }
+ auto col_res = ColumnInt32::create(input_rows_count);
+ auto& res_data = col_res->get_data();
- auto state = std::make_shared<UnicodeNormalizeState>();
- state->normalizer = normalizer;
- context->set_function_state(scope, state);
+ vector_vector(col_left_str, col_right_str, res_data, input_rows_count);
+
+ block.replace_by_position(result, std::move(col_res));
return Status::OK();
}
- Status execute_impl(FunctionContext* context, Block& block, const
ColumnNumbers& arguments,
- uint32_t result, size_t input_rows_count) const
override {
- auto* state = reinterpret_cast<UnicodeNormalizeState*>(
- context->get_function_state(FunctionContext::FRAGMENT_LOCAL));
- if (state == nullptr || state->normalizer == nullptr) {
- return Status::RuntimeError("unicode_normalize function state is
not initialized");
- }
-
- ColumnPtr col =
-
block.get_by_position(arguments[0]).column->convert_to_full_column_if_const();
- const auto* col_str = check_and_get_column<ColumnString>(col.get());
- if (col_str == nullptr) {
- return Status::RuntimeError("Illegal column {} of argument of
function {}",
-
block.get_by_position(arguments[0]).column->get_name(),
- get_name());
- }
+private:
+ // Helper: Convert UTF-8 bytes to Unicode code points
+ static void to_utf8_codepoints(const StringRef& str,
std::vector<uint32_t>& result) {
+ result.clear();
+ const char* p = str.data;
+ const char* end = str.data + str.size;
+
+ while (p < end) {
+ unsigned char c = static_cast<unsigned char>(*p);
+ uint32_t code_point = 0;
+ int bytes = 0;
+
+ if (c < 0x80) { // 1-byte sequence (ASCII)
+ bytes = 1;
+ code_point = c;
+ } else if ((c & 0xE0) == 0xC0) { // 2-byte sequence
+ bytes = 2;
+ code_point = c & 0x1F;
+ } else if ((c & 0xF0) == 0xE0) { // 3-byte sequence (Chinese, etc.)
+ bytes = 3;
+ code_point = c & 0x0F;
+ } else if ((c & 0xF8) == 0xF0) { // 4-byte sequence
+ bytes = 4;
+ code_point = c & 0x07;
+ } else {
+ // Invalid UTF-8, skip 1 byte
+ p++;
+ continue;
+ }
- const auto& data = col_str->get_chars();
- const auto& offsets = col_str->get_offsets();
+ // Boundary check
+ if (p + bytes > end) break;
- auto res = ColumnString::create();
- auto& res_data = res->get_chars();
- auto& res_offsets = res->get_offsets();
+ // Combine remaining bytes
+ for (int i = 1; i < bytes; ++i) {
+ code_point = (code_point << 6) | (p[i] & 0x3F);
+ }
+ result.push_back(code_point);
+ p += bytes;
+ }
+ }
- size_t rows = offsets.size();
- res_offsets.resize(rows);
+ static int32_t calculate_levenshtein(const StringRef& str1, const
StringRef& str2) {
+ // Parse UTF-8 strings to code points
+ std::vector<uint32_t> source, target;
+ to_utf8_codepoints(str1, source);
+ to_utf8_codepoints(str2, target);
- std::string tmp;
- for (size_t i = 0; i < rows; ++i) {
- const char* begin = reinterpret_cast<const char*>(&data[offsets[i
- 1]]);
- size_t len = offsets[i] - offsets[i - 1];
+ const size_t len1 = source.size();
+ const size_t len2 = target.size();
- normalize_one(state->normalizer, begin, len, tmp);
- StringOP::push_value_string(tmp, i, res_data, res_offsets);
- }
+ // Edge cases for empty strings
+ if (len1 == 0) return static_cast<int32_t>(len2);
Review Comment:
surround all stmt under `if`/`for` with braces
##########
be/src/vec/functions/function_string.h:
##########
@@ -5261,146 +5258,132 @@ class FunctionCrc32Internal : public IFunction {
}
};
-class FunctionUnicodeNormalize : public IFunction {
+class FunctionStringLevenshtein : public IFunction {
public:
- static constexpr auto name = "unicode_normalize";
-
- static FunctionPtr create() { return
std::make_shared<FunctionUnicodeNormalize>(); }
-
+ static constexpr auto name = "levenshtein";
+ static FunctionPtr create() { return
std::make_shared<FunctionStringLevenshtein>(); }
String get_name() const override { return name; }
-
size_t get_number_of_arguments() const override { return 2; }
-
DataTypePtr get_return_type_impl(const DataTypes& arguments) const
override {
- if (arguments.size() != 2 ||
!is_string_type(arguments[0]->get_primitive_type()) ||
- !is_string_type(arguments[1]->get_primitive_type())) {
- throw doris::Exception(ErrorCode::INVALID_ARGUMENT,
- "Illegal type {} and {} of arguments of
function {}",
- arguments[0]->get_name(),
arguments[1]->get_name(), get_name());
- }
- return arguments[0];
+ return std::make_shared<DataTypeInt32>();
}
+ bool use_default_implementation_for_nulls() const override { return true; }
- ColumnNumbers get_arguments_that_are_always_constant() const override {
return {1}; }
+ Status execute_impl(FunctionContext* context, Block& block, const
ColumnNumbers& arguments,
+ uint32_t result, size_t input_rows_count) const
override {
+ // Convert input columns to full columns
+ auto col_left =
+
block.get_by_position(arguments[0]).column->convert_to_full_column_if_const();
Review Comment:
shouldn't directly convert to full column. impl `vector_const` and
`const_vector` like other functions
##########
be/src/vec/functions/function_string.h:
##########
@@ -5261,146 +5258,132 @@ class FunctionCrc32Internal : public IFunction {
}
};
-class FunctionUnicodeNormalize : public IFunction {
+class FunctionStringLevenshtein : public IFunction {
public:
- static constexpr auto name = "unicode_normalize";
-
- static FunctionPtr create() { return
std::make_shared<FunctionUnicodeNormalize>(); }
-
+ static constexpr auto name = "levenshtein";
+ static FunctionPtr create() { return
std::make_shared<FunctionStringLevenshtein>(); }
String get_name() const override { return name; }
-
size_t get_number_of_arguments() const override { return 2; }
-
DataTypePtr get_return_type_impl(const DataTypes& arguments) const
override {
- if (arguments.size() != 2 ||
!is_string_type(arguments[0]->get_primitive_type()) ||
- !is_string_type(arguments[1]->get_primitive_type())) {
- throw doris::Exception(ErrorCode::INVALID_ARGUMENT,
- "Illegal type {} and {} of arguments of
function {}",
- arguments[0]->get_name(),
arguments[1]->get_name(), get_name());
- }
- return arguments[0];
+ return std::make_shared<DataTypeInt32>();
}
+ bool use_default_implementation_for_nulls() const override { return true; }
- ColumnNumbers get_arguments_that_are_always_constant() const override {
return {1}; }
+ Status execute_impl(FunctionContext* context, Block& block, const
ColumnNumbers& arguments,
+ uint32_t result, size_t input_rows_count) const
override {
+ // Convert input columns to full columns
+ auto col_left =
+
block.get_by_position(arguments[0]).column->convert_to_full_column_if_const();
Review Comment:
oh. if you use `FunctionBinaryToType` and `StringFunctionImpl` to refactor
this. then dont be worry about const process.
##########
be/test/vec/function/function_levenshtein_test.cpp:
##########
@@ -0,0 +1,71 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+#include <gtest/gtest.h>
+
+#include <string>
+#include <vector>
+
+#include "function_test_util.h"
+#include "vec/data_types/data_type_number.h"
+#include "vec/data_types/data_type_string.h"
+
+using namespace doris;
+using namespace doris::vectorized;
+
+TEST(function_string_test, function_levenshtein_comprehensive_test) {
+ std::string func_name = "levenshtein";
+
+ InputTypeSet input_types = {PrimitiveType::TYPE_VARCHAR,
PrimitiveType::TYPE_VARCHAR};
+
+ DataSet data_set = {{{std::string("kitten"), std::string("sitting")},
(int32_t)3},
+ {{std::string("saturday"), std::string("sunday")},
(int32_t)3},
+ {{std::string("rosettacode"),
std::string("raisethysword")}, (int32_t)8},
+
+ {{std::string("test"), std::string("test")},
(int32_t)0},
+
+ {{std::string("cat"), std::string("bat")}, (int32_t)1},
+ {{std::string("abc"), std::string("xyz")}, (int32_t)3},
+
+ {{std::string("book"), std::string("books")},
(int32_t)1},
+ {{std::string("test"), std::string("mytest")},
(int32_t)2},
+
+ {{std::string("apple"), std::string("app")},
(int32_t)2},
+
+ {{std::string(""), std::string("")}, (int32_t)0},
+ {{std::string("a"), std::string("")}, (int32_t)1},
+ {{std::string(""), std::string("abc")}, (int32_t)3},
+
+ {{std::string("A"), std::string("a")}, (int32_t)1},
+ {{std::string("Doris"), std::string("doris")},
(int32_t)1},
+
+ {{std::string("a-b-c"), std::string("a_b_c")},
(int32_t)2},
+ {{std::string("1234567890"),
std::string("1234567890")}, (int32_t)0},
+
+ {{std::string("中"), std::string("中")}, (int32_t)0},
+
+ {{std::string("中国"), std::string("中")}, (int32_t)3},
Review Comment:
the result should be 1?
##########
be/src/vec/functions/function_string.h:
##########
@@ -5261,146 +5258,132 @@ class FunctionCrc32Internal : public IFunction {
}
};
-class FunctionUnicodeNormalize : public IFunction {
+class FunctionStringLevenshtein : public IFunction {
public:
- static constexpr auto name = "unicode_normalize";
-
- static FunctionPtr create() { return
std::make_shared<FunctionUnicodeNormalize>(); }
-
+ static constexpr auto name = "levenshtein";
+ static FunctionPtr create() { return
std::make_shared<FunctionStringLevenshtein>(); }
String get_name() const override { return name; }
-
size_t get_number_of_arguments() const override { return 2; }
-
DataTypePtr get_return_type_impl(const DataTypes& arguments) const
override {
- if (arguments.size() != 2 ||
!is_string_type(arguments[0]->get_primitive_type()) ||
- !is_string_type(arguments[1]->get_primitive_type())) {
- throw doris::Exception(ErrorCode::INVALID_ARGUMENT,
- "Illegal type {} and {} of arguments of
function {}",
- arguments[0]->get_name(),
arguments[1]->get_name(), get_name());
- }
- return arguments[0];
+ return std::make_shared<DataTypeInt32>();
}
+ bool use_default_implementation_for_nulls() const override { return true; }
- ColumnNumbers get_arguments_that_are_always_constant() const override {
return {1}; }
+ Status execute_impl(FunctionContext* context, Block& block, const
ColumnNumbers& arguments,
+ uint32_t result, size_t input_rows_count) const
override {
+ // Convert input columns to full columns
+ auto col_left =
+
block.get_by_position(arguments[0]).column->convert_to_full_column_if_const();
+ auto col_right =
+
block.get_by_position(arguments[1]).column->convert_to_full_column_if_const();
- Status open(FunctionContext* context, FunctionContext::FunctionStateScope
scope) override {
- if (scope == FunctionContext::THREAD_LOCAL) {
- return Status::OK();
- }
+ const auto* col_left_str =
check_and_get_column<ColumnString>(col_left.get());
+ const auto* col_right_str =
check_and_get_column<ColumnString>(col_right.get());
- if (!context->is_col_constant(1)) {
- return Status::InvalidArgument(
- "The second argument 'mode' of function {} must be
constant", get_name());
- }
-
- auto* const_col = context->get_constant_col(1);
- auto mode_ref = const_col->column_ptr->get_data_at(0);
- std::string lower_mode =
doris::to_lower(std::string(doris::trim(mode_ref.to_string())));
-
- UErrorCode status = U_ZERO_ERROR;
- const icu::Normalizer2* normalizer = nullptr;
-
- if (lower_mode == "nfc") {
- normalizer = icu::Normalizer2::getInstance(nullptr, "nfc",
UNORM2_COMPOSE, status);
- } else if (lower_mode == "nfd") {
- normalizer = icu::Normalizer2::getNFDInstance(status);
- } else if (lower_mode == "nfkc") {
- normalizer = icu::Normalizer2::getInstance(nullptr, "nfkc",
UNORM2_COMPOSE, status);
- } else if (lower_mode == "nfkd") {
- normalizer = icu::Normalizer2::getNFKDInstance(status);
- } else if (lower_mode == "nfkc_cf") {
- normalizer = icu::Normalizer2::getInstance(nullptr, "nfkc_cf",
UNORM2_COMPOSE, status);
- } else {
- return Status::InvalidArgument(
- "Invalid normalization mode '{}' for function {}. "
- "Supported modes: NFC, NFD, NFKC, NFKD, NFKC_CF",
- lower_mode, get_name());
+ if (!col_left_str || !col_right_str) {
+ return Status::InternalError("Levenshtein arguments must be
String");
}
- if (U_FAILURE(status) || normalizer == nullptr) {
- return Status::InvalidArgument(
- "Failed to get normalizer instance for mode '{}' in
function {}: {}",
- lower_mode, get_name(), u_errorName(status));
- }
+ auto col_res = ColumnInt32::create(input_rows_count);
+ auto& res_data = col_res->get_data();
- auto state = std::make_shared<UnicodeNormalizeState>();
- state->normalizer = normalizer;
- context->set_function_state(scope, state);
+ vector_vector(col_left_str, col_right_str, res_data, input_rows_count);
+
+ block.replace_by_position(result, std::move(col_res));
return Status::OK();
}
- Status execute_impl(FunctionContext* context, Block& block, const
ColumnNumbers& arguments,
- uint32_t result, size_t input_rows_count) const
override {
- auto* state = reinterpret_cast<UnicodeNormalizeState*>(
- context->get_function_state(FunctionContext::FRAGMENT_LOCAL));
- if (state == nullptr || state->normalizer == nullptr) {
- return Status::RuntimeError("unicode_normalize function state is
not initialized");
- }
-
- ColumnPtr col =
-
block.get_by_position(arguments[0]).column->convert_to_full_column_if_const();
- const auto* col_str = check_and_get_column<ColumnString>(col.get());
- if (col_str == nullptr) {
- return Status::RuntimeError("Illegal column {} of argument of
function {}",
-
block.get_by_position(arguments[0]).column->get_name(),
- get_name());
- }
+private:
+ // Helper: Convert UTF-8 bytes to Unicode code points
+ static void to_utf8_codepoints(const StringRef& str,
std::vector<uint32_t>& result) {
+ result.clear();
+ const char* p = str.data;
+ const char* end = str.data + str.size;
+
+ while (p < end) {
+ unsigned char c = static_cast<unsigned char>(*p);
+ uint32_t code_point = 0;
+ int bytes = 0;
+
+ if (c < 0x80) { // 1-byte sequence (ASCII)
+ bytes = 1;
+ code_point = c;
+ } else if ((c & 0xE0) == 0xC0) { // 2-byte sequence
+ bytes = 2;
+ code_point = c & 0x1F;
+ } else if ((c & 0xF0) == 0xE0) { // 3-byte sequence (Chinese, etc.)
+ bytes = 3;
+ code_point = c & 0x0F;
+ } else if ((c & 0xF8) == 0xF0) { // 4-byte sequence
+ bytes = 4;
+ code_point = c & 0x07;
+ } else {
+ // Invalid UTF-8, skip 1 byte
+ p++;
+ continue;
+ }
- const auto& data = col_str->get_chars();
- const auto& offsets = col_str->get_offsets();
+ // Boundary check
+ if (p + bytes > end) break;
- auto res = ColumnString::create();
- auto& res_data = res->get_chars();
- auto& res_offsets = res->get_offsets();
+ // Combine remaining bytes
+ for (int i = 1; i < bytes; ++i) {
+ code_point = (code_point << 6) | (p[i] & 0x3F);
+ }
+ result.push_back(code_point);
+ p += bytes;
+ }
+ }
- size_t rows = offsets.size();
- res_offsets.resize(rows);
+ static int32_t calculate_levenshtein(const StringRef& str1, const
StringRef& str2) {
+ // Parse UTF-8 strings to code points
+ std::vector<uint32_t> source, target;
+ to_utf8_codepoints(str1, source);
+ to_utf8_codepoints(str2, target);
- std::string tmp;
- for (size_t i = 0; i < rows; ++i) {
- const char* begin = reinterpret_cast<const char*>(&data[offsets[i
- 1]]);
- size_t len = offsets[i] - offsets[i - 1];
+ const size_t len1 = source.size();
+ const size_t len2 = target.size();
- normalize_one(state->normalizer, begin, len, tmp);
- StringOP::push_value_string(tmp, i, res_data, res_offsets);
- }
+ // Edge cases for empty strings
+ if (len1 == 0) return static_cast<int32_t>(len2);
+ if (len2 == 0) return static_cast<int32_t>(len1);
- block.replace_by_position(result, std::move(res));
- return Status::OK();
- }
+ // DP vectors
+ std::vector<int32_t> prev_dp(len2 + 1);
Review Comment:
these name is meaningless. could you replace them by names which tell us
what it stands for? or add some comment
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]