-
Notifications
You must be signed in to change notification settings - Fork 9k
Expand file tree
/
Copy pathFunctionFile.cpp
More file actions
217 lines (174 loc) · 7.97 KB
/
Copy pathFunctionFile.cpp
File metadata and controls
217 lines (174 loc) · 7.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
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
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
#include <Columns/ColumnNullable.h>
#include <Columns/ColumnString.h>
#include <Columns/ColumnConst.h>
#include <Columns/IColumn.h>
#include <Functions/FunctionFactory.h>
#include <Access/Common/AccessFlags.h>
#include <DataTypes/DataTypeString.h>
#include <DataTypes/DataTypeNullable.h>
#include <IO/ReadBufferFromFile.h>
#include <IO/WriteBufferFromVector.h>
#include <IO/copyData.h>
#include <Interpreters/Context.h>
#include <Common/filesystemHelpers.h>
#include <filesystem>
#include <Functions/FunctionHelpers.h>
#include <Core/ColumnWithTypeAndName.h>
namespace fs = std::filesystem;
namespace DB
{
namespace ErrorCodes
{
extern const int ILLEGAL_COLUMN;
extern const int DATABASE_ACCESS_DENIED;
}
namespace
{
bool isStringOrNull(const IDataType & type)
{
return isString(type) || type.onlyNull();
}
}
/// A function to read file as a string.
class FunctionFile final : public IFunction
{
public:
static constexpr auto name = "file";
static FunctionPtr create(ContextPtr context)
{
if (context && context->getApplicationType() != Context::ApplicationType::LOCAL)
context->checkAccess(AccessType::READ, toStringSource(AccessTypeObjects::Source::FILE));
return std::make_shared<FunctionFile>();
}
bool isVariadic() const override { return true; }
String getName() const override { return name; }
size_t getNumberOfArguments() const override { return 0; }
bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return true; }
bool isDeterministic() const override { return false; }
bool isDeterministicInScopeOfQuery() const override { return false; }
DataTypePtr getReturnTypeImpl(const ColumnsWithTypeAndName & arguments) const override
{
FunctionArgumentDescriptors mandatory_args{
{"path", &isString, nullptr, "String"}
};
FunctionArgumentDescriptors optional_args{
{"default", &isStringOrNull, nullptr, "String or Null"}
};
validateFunctionArguments(*this, arguments, mandatory_args, optional_args);
auto ret = std::make_shared<DataTypeString>();
if (arguments.size() == 2 && arguments[1].type->onlyNull())
return makeNullable(ret);
return ret;
}
DataTypePtr getReturnTypeForDefaultImplementationForDynamic() const override
{
return std::make_shared<DataTypeString>();
}
ColumnNumbers getArgumentsThatAreAlwaysConstant() const override { return {1}; }
bool useDefaultImplementationForNulls() const override { return false; }
bool useDefaultImplementationForConstants() const override { return true; }
ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const override
{
const ColumnPtr column = arguments[0].column;
const ColumnString * column_src = checkAndGetColumn<ColumnString>(column.get());
if (!column_src)
throw Exception(ErrorCodes::ILLEGAL_COLUMN,
"Illegal column {} of argument of function {}", arguments[0].column->getName(), getName());
String default_result;
ColumnUInt8::MutablePtr col_null_map_to;
ColumnUInt8::Container * vec_null_map_to [[maybe_unused]] = nullptr;
if (arguments.size() == 2)
{
if (result_type->isNullable())
{
col_null_map_to = ColumnUInt8::create(input_rows_count, false);
vec_null_map_to = &col_null_map_to->getData();
}
else
{
const auto & default_column = arguments[1].column;
const ColumnConst * default_col = checkAndGetColumn<ColumnConst>(default_column.get());
if (!default_col)
throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}",
arguments[1].column->getName(), getName());
default_result = default_col->getValue<String>();
}
}
auto result = ColumnString::create();
auto & res_chars = result->getChars();
auto & res_offsets = result->getOffsets();
res_offsets.resize(input_rows_count);
const auto & context = Context::getGlobalContextInstance();
fs::path user_files_absolute_path = fs::canonical(fs::path(context->getUserFilesPath()));
std::string user_files_absolute_path_string = user_files_absolute_path.string();
// If run in Local mode, no need for path checking.
bool need_check = context->getApplicationType() != Context::ApplicationType::LOCAL;
for (size_t row = 0; row < input_rows_count; ++row)
{
std::string_view filename = column_src->getDataAt(row);
fs::path file_path(filename.data(), filename.data() + filename.size());
if (file_path.is_relative())
file_path = user_files_absolute_path / file_path;
/// Do not use fs::canonical or fs::weakly_canonical.
/// Otherwise it will not allow to work with symlinks in `user_files_path` directory.
file_path = fs::absolute(file_path).lexically_normal();
try
{
if (need_check && !fileOrSymlinkPathStartsWith(file_path.string(), user_files_absolute_path_string))
throw Exception(ErrorCodes::DATABASE_ACCESS_DENIED, "File is not inside {}", user_files_absolute_path.string());
ReadBufferFromFile in(file_path);
auto out = WriteBufferFromVector<ColumnString::Chars>(res_chars, AppendModeTag{});
copyData(in, out);
}
catch (...)
{
if (arguments.size() == 1)
throw;
if (vec_null_map_to)
(*vec_null_map_to)[row] = true;
else
res_chars.insert(default_result.data(), default_result.data() + default_result.size());
}
res_offsets[row] = res_chars.size();
}
if (vec_null_map_to)
return ColumnNullable::create(std::move(result), std::move(col_null_map_to));
return result;
}
};
REGISTER_FUNCTION(File)
{
FunctionDocumentation::Description description = R"(
Reads a file as a string and loads the data into the specified column.
The file content is not interpreted.
Also see the [`file`](/reference/functions/table-functions/file) table function.
)";
FunctionDocumentation::Syntax syntax = "file(path[, default])";
FunctionDocumentation::Arguments arguments = {
{"path", "The path of the file relative to the `user_files_path`. Supports wildcards `*`, `**`, `?`, `{abc,def}` and `{N..M}` where `N`, `M` are numbers and `'abc', 'def'` are strings.", {"String"}},
{"default", "The value returned if the file does not exist or cannot be accessed.", {"String", "NULL"}}
};
FunctionDocumentation::ReturnedValue returned_value = {"Returns the file content as a string.", {"String"}};
FunctionDocumentation::Examples examples = {
{
"Insert files into a table",
R"(
INSERT INTO FUNCTION file('a.txt', 'RawBLOB') SELECT 'Hello' SETTINGS engine_file_truncate_on_insert = 1;
INSERT INTO FUNCTION file('b.txt', 'RawBLOB') SELECT 'World!' SETTINGS engine_file_truncate_on_insert = 1;
CREATE TABLE data (a String, b String) ENGINE = Memory;
INSERT INTO data SELECT file('a.txt'), file('b.txt');
SELECT * FROM data;
)",
R"(
┌─a─────┬─b──────┐
│ Hello │ World! │
└───────┴────────┘
)"
}
};
FunctionDocumentation::IntroducedIn introduced_in = {21, 3};
FunctionDocumentation::Category category = FunctionDocumentation::Category::Other;
FunctionDocumentation documentation = {description, syntax, arguments, {}, returned_value, examples, introduced_in, category};
factory.registerFunction<FunctionFile>(documentation);
}
}