diff --git a/dbms/src/Functions/basename.cpp b/dbms/src/Functions/basename.cpp new file mode 100644 index 00000000000..53320014766 --- /dev/null +++ b/dbms/src/Functions/basename.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +#include + +namespace DB +{ + +/** Extract substring after the last slash or backslash. + * If there are no slashes, return the string unchanged. + * It is used to extract filename from path. + */ +struct ExtractBasename +{ + static size_t getReserveLengthForElement() { return 16; } /// Just a guess. + + static void execute(Pos data, size_t size, Pos & res_data, size_t & res_size) + { + res_data = data; + res_size = size; + + Pos pos = data; + Pos end = pos + size; + + if ((pos = find_last_symbols_or_null<'/', '\\'>(pos, end))) + { + ++pos; + res_data = pos; + res_size = end - pos; + } + } +}; + +struct NameBasename { static constexpr auto name = "basename"; }; +using FunctionBasename = FunctionStringToString, NameBasename>; + +void registerFunctionBasename(FunctionFactory & factory) +{ + factory.registerFunction(); +} + +} diff --git a/dbms/src/Functions/registerFunctionsMiscellaneous.cpp b/dbms/src/Functions/registerFunctionsMiscellaneous.cpp index d985fb6bf97..05e888dbbe9 100644 --- a/dbms/src/Functions/registerFunctionsMiscellaneous.cpp +++ b/dbms/src/Functions/registerFunctionsMiscellaneous.cpp @@ -42,6 +42,7 @@ void registerFunctionLowCardinalityKeys(FunctionFactory &); void registerFunctionsIn(FunctionFactory &); void registerFunctionJoinGet(FunctionFactory &); void registerFunctionFilesystem(FunctionFactory &); +void registerFunctionBasename(FunctionFactory &); void registerFunctionsMiscellaneous(FunctionFactory & factory) { @@ -84,6 +85,7 @@ void registerFunctionsMiscellaneous(FunctionFactory & factory) registerFunctionsIn(factory); registerFunctionJoinGet(factory); registerFunctionFilesystem(factory); + registerFunctionBasename(factory); } } diff --git a/dbms/tests/queries/0_stateless/00938_basename.reference b/dbms/tests/queries/0_stateless/00938_basename.reference new file mode 100644 index 00000000000..37da7973757 --- /dev/null +++ b/dbms/tests/queries/0_stateless/00938_basename.reference @@ -0,0 +1,5 @@ +bash + +bash +test_file +script.php diff --git a/dbms/tests/queries/0_stateless/00938_basename.sql b/dbms/tests/queries/0_stateless/00938_basename.sql new file mode 100644 index 00000000000..cea11e9a479 --- /dev/null +++ b/dbms/tests/queries/0_stateless/00938_basename.sql @@ -0,0 +1,5 @@ +SELECT basename('/usr/bin/bash'); +SELECT basename('/usr/bin/bash/'); +SELECT basename('bash'); +SELECT basename('C:\\\\Users\\Documents\\test_file'); +SELECT basename(path('http://example.com/folder_1/folder_2/script.php'))