forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathHTTPQueryConstructor.cpp
More file actions
410 lines (369 loc) · 16 KB
/
Copy pathHTTPQueryConstructor.cpp
File metadata and controls
410 lines (369 loc) · 16 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
218
219
220
221
222
223
224
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
#include <Server/HTTPQueryConstructor.h>
#include <Common/Exception.h>
#include <Common/StringUtils.h>
#include <Common/quoteString.h>
#include <Formats/FormatFactory.h>
#include <IO/CompressionMethod.h>
#include <Poco/String.h>
#include <Poco/URI.h>
#include <array>
namespace DB
{
namespace ErrorCodes
{
extern const int BAD_ARGUMENTS;
extern const int UNKNOWN_FORMAT;
extern const int UNKNOWN_TABLE;
}
namespace
{
/// Returns the canonical (registered) format name from a case-insensitive lookup.
String findFormatCaseInsensitive(const String & candidate)
{
String lower = Poco::toLower(candidate);
for (const auto & [name, _] : FormatFactory::instance().getAllFormats())
if (Poco::toLower(name) == lower)
return name;
return {};
}
/// Split a *raw* (percent-encoded) path on '/' producing non-empty components, percent-decoding each
/// component only after the split. Decoding after splitting keeps an encoded slash (`%2F`) as data inside
/// a single component (e.g. a filter value like `a=foo%2Fbar`, or a back-quoted name `` `a%2Fb` ``),
/// instead of turning it into a component boundary.
Strings splitPathComponents(const String & path)
{
Strings result;
String current;
auto flush = [&]()
{
if (!current.empty())
{
String decoded;
Poco::URI::decode(current, decoded);
result.push_back(decoded);
current.clear();
}
};
for (char c : path)
{
if (c == '/')
flush();
else
current += c;
}
flush();
return result;
}
/// If the component contains one of the supported comparison operators, return the parsed filter
/// as a SQL expression (with the identifier quoted). Returns empty string if not a filter.
/// Operators in order of attempt (longer first): `>=`, `<=`, `!=`, `<>`, `>`, `<`, `=`.
String tryParseFilterComponent(const String & component)
{
static constexpr std::array<const char *, 7> ops = {">=", "<=", "!=", "<>", ">", "<", "="};
for (const char * op : ops)
{
auto pos = component.find(op);
if (pos == String::npos)
continue;
/// Don't match if op starts at 0 (no name) or extends to end (no value).
size_t op_len = strlen(op);
if (pos == 0 || pos + op_len >= component.size())
continue;
String name = component.substr(0, pos);
String value = component.substr(pos + op_len);
String sql_op(op);
/// Translate `<>` to `!=` for consistency.
if (sql_op == "<>")
sql_op = "!=";
return "(" + backQuoteIfNeed(name) + " " + sql_op + " " + quoteString(value) + ")";
}
return {};
}
/// A fully back-quoted component (`` `name` ``) is an explicit identifier (a database/table name), so it
/// must be treated as a name — never a filter — even when it contains characters that look like a filter
/// operator, e.g. `` `a=1` `` or `` `a>1` ``. Otherwise such a table name is misparsed as a filter.
bool isFullyBackQuotedComponent(const String & component)
{
return component.size() >= 2 && component.front() == '`' && component.back() == '`';
}
/// If `component` is fully back-quoted (`` `name` ``), return the identifier with the surrounding
/// back-quotes removed and doubled back-quotes unescaped (`` `` `` -> `` ` ``), as in SQL identifier
/// quoting. Otherwise return it unchanged.
String unquoteBackQuotedComponent(const String & component)
{
if (!isFullyBackQuotedComponent(component))
return component;
const String inner = component.substr(1, component.size() - 2);
String unquoted;
unquoted.reserve(inner.size());
for (size_t i = 0; i < inner.size(); ++i)
{
if (inner[i] == '`' && i + 1 < inner.size() && inner[i + 1] == '`')
{
unquoted += '`';
++i;
}
else
unquoted += inner[i];
}
return unquoted;
}
}
HTTPPathInfo parseHTTPPath(const String & path, bool allow_database, bool allow_table, bool allow_filters)
{
HTTPPathInfo result;
if (path.empty() || path == "/")
return result;
Strings components = splitPathComponents(path);
if (components.empty())
return result;
/// Walk components in order. Last non-filter component (if any) may be the table.
/// Preceding non-filter components include at most one database.
/// Filter components can be intermixed.
int last_non_filter_index = -1;
/// First pass: identify filters and non-filter components.
std::vector<int> non_filter_indices;
std::vector<String> per_component_filter; // for each index, parsed filter or empty
per_component_filter.resize(components.size());
for (size_t i = 0; i < components.size(); ++i)
{
String filter_expr;
if (allow_filters && !isFullyBackQuotedComponent(components[i]))
filter_expr = tryParseFilterComponent(components[i]);
if (!filter_expr.empty())
{
per_component_filter[i] = filter_expr;
}
else
{
non_filter_indices.push_back(static_cast<int>(i));
last_non_filter_index = static_cast<int>(i);
}
}
/// Determine table component
int table_index = -1;
if (allow_table && last_non_filter_index >= 0)
{
table_index = last_non_filter_index;
}
/// Determine database component (everything else before the table among non-filter indices)
std::vector<int> db_indices;
for (int idx : non_filter_indices)
if (idx != table_index)
db_indices.push_back(idx);
if (!allow_database && !db_indices.empty())
{
/// Non-filter components other than the table cannot be claimed when `http_allow_database_as_path`
/// is off — leave them unclaimed and return an empty result. The path is effectively ignored
/// and the request proceeds as if it had hit the root URL.
return {};
}
if (db_indices.size() > 1)
{
/// A path this deep names no resource: the path form is `/database/table[.format[.compression]]`,
/// so there is nothing for a third component to be. Report it as "not found" rather than as a
/// malformed request, so that enabling `http_allow_path_requests` does not turn the plain 404 an
/// unmatched URL used to get into a 400 (`UNKNOWN_TABLE` maps to HTTP 404, `BAD_ARGUMENTS` to 400).
throw Exception(ErrorCodes::UNKNOWN_TABLE,
"There is no table at the HTTP URL path: it has more than one database component "
"('{}' and '{}'). The path form is /database/table[.format[.compression]].",
components[db_indices[0]], components[db_indices[1]]);
}
/// Special case: if there is exactly one non-filter component and allow_database is on
/// but allow_table is off, that single component is the database (not the table).
if (!allow_table && allow_database && non_filter_indices.size() == 1)
{
result.database = unquoteBackQuotedComponent(components[non_filter_indices[0]]);
}
else
{
if (!db_indices.empty())
result.database = unquoteBackQuotedComponent(components[db_indices[0]]);
if (table_index >= 0)
{
/// Parse table[.format[.compression]] from the last component.
const String & raw = components[table_index];
/// A fully back-quoted component is a *literal* table name: its dots are part of the name
/// and no format/compression suffix is stripped from it. This mirrors SQL identifier quoting
/// (where `db.table` is always `database.identifier` and a dotted name must be back-quoted)
/// and is the escape hatch for a table whose name ends in (or contains) a registered format
/// or compression token. For example `` /db/`events.JSON` `` reads the table named
/// `events.JSON`, whereas the unquoted `/db/events.JSON` reads table `events` with format
/// `JSON`. When the name is back-quoted, specify the format/compression via the `format` /
/// `compression` URL parameters (or the `format` setting) instead of a path suffix.
/// A backtick travels in a URL percent-encoded as `%60`; `HTTPHandler` URL-decodes the path
/// before calling this, so `/db/%60events.JSON%60` arrives here as `` `events.JSON` ``.
if (isFullyBackQuotedComponent(raw))
{
const String unquoted = unquoteBackQuotedComponent(raw);
result.table = unquoted;
result.format = {};
result.compression = {};
result.filename_for_disposition = unquoted;
}
else
{
/// Try splitting from the right.
String table_part = raw;
String format_part;
String compression_part;
String disposition_filename = raw;
auto last_dot = table_part.rfind('.');
if (last_dot != String::npos)
{
String maybe_extension = table_part.substr(last_dot + 1);
String maybe_compression_name = canonicalizeCompressionExtension(maybe_extension);
if (!maybe_compression_name.empty())
{
compression_part = maybe_compression_name;
/// Canonicalize the compression extension in the disposition filename so an accepted
/// alias (`.zstd` / `.gzip` / `.lzma` / `.bzip2`) is not duplicated when `HTTPHandler`
/// appends the canonical suffix (`.zst` / `.gz` / `.xz` / `.bz2`). For example
/// `/db/hits.Native.zstd` yields the filename `hits.Native.zst`, not `hits.Native.zstd.zst`.
if (maybe_compression_name != maybe_extension)
disposition_filename = raw.substr(0, last_dot + 1) + maybe_compression_name;
table_part = table_part.substr(0, last_dot);
last_dot = table_part.rfind('.');
if (last_dot != String::npos)
{
String fmt_candidate = table_part.substr(last_dot + 1);
String canonical_format = findFormatCaseInsensitive(fmt_candidate);
if (canonical_format.empty())
{
throw Exception(ErrorCodes::UNKNOWN_FORMAT,
"Unknown format '{}' in URL path. Compression cannot be specified without a known format.", fmt_candidate);
}
format_part = canonical_format;
table_part = table_part.substr(0, last_dot);
}
else
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Compression extension '{}' specified without a format in URL path.", compression_part);
}
}
else
{
/// Maybe just a format extension (no compression).
String canonical_format = findFormatCaseInsensitive(maybe_extension);
if (!canonical_format.empty())
{
format_part = canonical_format;
table_part = table_part.substr(0, last_dot);
}
/// Otherwise leave it as part of the table name.
}
}
result.table = table_part;
result.format = format_part;
result.compression = compression_part;
result.filename_for_disposition = disposition_filename;
}
}
}
/// Collect filters in their path order.
for (size_t i = 0; i < components.size(); ++i)
if (!per_component_filter[i].empty())
result.path_filters.push_back(per_component_filter[i]);
return result;
}
String parseURLParameterAsFilter(const String & name, const String & value)
{
if (name.empty())
return {};
/// Case 1: HTMLForm splits a URL parameter on the first `=`. For two-character operators
/// that end in `=` (`!=`, `>=`, `<=`), the operator's `=` ends up as that separator, leaving
/// the leading character of the operator stuck to the end of the name and the literal in the value.
/// Examples:
/// `?a!=2` -> name `a!` and value `2` -> `a != 2`
/// `?a>=2` -> name `a>` and value `2` -> `a >= 2`
/// `?a<=2` -> name `a<` and value `2` -> `a <= 2`
if (name.size() > 1
&& (name.back() == '!' || name.back() == '>' || name.back() == '<'))
{
char op_char = name.back();
String identifier = name.substr(0, name.size() - 1);
if (!identifier.empty())
{
String op;
if (op_char == '!')
op = "!=";
else if (op_char == '>')
op = ">=";
else /* '<' */
op = "<=";
return "(" + backQuoteIfNeed(identifier) + " " + op + " " + quoteString(value) + ")";
}
}
/// Case 2: The full operator survived inside `name` because the URL had no `=` to split on
/// (e.g. `?a>2`, `?a<>2`, `?f(x)>3`). Treat the reassembled `name[=value]` as a SQL expression.
static constexpr std::array<const char *, 6> compare_ops = {">=", "<=", "!=", "<>", ">", "<"};
auto has_compare_op = [&](const String & s)
{
for (const char * op : compare_ops)
if (s.contains(op))
return true;
return false;
};
if (has_compare_op(name))
{
String full = value.empty() ? name : name + "=" + value;
return "(" + full + ")";
}
/// Case 3: Plain `name=value` -> `name = value` with quoted literal.
return "(" + backQuoteIfNeed(name) + " = " + quoteString(value) + ")";
}
bool isBinaryOutputFormat(const String & format_name)
{
if (format_name.empty())
return false;
try
{
String content_type = FormatFactory::instance().getContentType(format_name, {});
/// Common binary content types.
if (startsWith(content_type, "application/octet-stream"))
return true;
if (startsWith(content_type, "application/x-parquet"))
return true;
/// Heuristic: any content type that starts with "application/" but isn't json/xml/x-www-form is binary-ish.
if (startsWith(content_type, "application/"))
{
if (content_type.contains("json"))
return false;
if (content_type.contains("xml"))
return false;
return true;
}
return false;
}
catch (...) /// Ok: unknown / malformed format name — fall back to "not binary".
{
return false;
}
}
String canonicalizeCompressionExtension(const String & ext)
{
String lower = Poco::toLower(ext);
/// Supported compression methods recognized by `wrapWriteBufferWithCompressionMethod`.
/// Map common file extensions to the canonical name expected by `chooseCompressionMethod`.
if (lower == "gz" || lower == "gzip")
return "gz";
if (lower == "br")
return "br";
if (lower == "zst" || lower == "zstd")
return "zst";
if (lower == "xz" || lower == "lzma")
return "xz";
if (lower == "lz4")
return "lz4";
if (lower == "bz2" || lower == "bzip2")
return "bz2";
if (lower == "deflate")
return "deflate";
/// NOTE: Snappy is intentionally not listed: it has only a read wrapper
/// (`HadoopSnappyReadBuffer`), and `wrapWriteBufferWithCompressionMethod` throws
/// `NOT_IMPLEMENTED` for it. Advertising `.snappy` as a response-compression extension would let
/// `/table.CSV.snappy` parse as valid and then fail only at response-buffer setup.
return {};
}
}