-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathparse_functions.cpp
More file actions
360 lines (299 loc) · 12.3 KB
/
parse_functions.cpp
File metadata and controls
360 lines (299 loc) · 12.3 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
#include "parse_functions.hpp"
#include "duckdb.hpp"
#include "duckdb/parser/parser.hpp"
#include "duckdb/parser/statement/select_statement.hpp"
#include "duckdb/parser/query_node/cte_node.hpp"
#include "duckdb/parser/query_node/select_node.hpp"
#include "duckdb/parser/expression/function_expression.hpp"
#include "duckdb/parser/expression/window_expression.hpp"
#include "duckdb/parser/parsed_expression_iterator.hpp"
#include "duckdb/parser/result_modifier.hpp"
#include "duckdb/function/scalar/nested_functions.hpp"
namespace duckdb {
enum class FunctionContext {
Select,
Where,
Having,
OrderBy,
GroupBy,
Join,
WindowFunction,
Nested
};
inline const char *ToString(FunctionContext context) {
switch (context) {
case FunctionContext::Select: return "select";
case FunctionContext::Where: return "where";
case FunctionContext::Having: return "having";
case FunctionContext::OrderBy: return "order_by";
case FunctionContext::GroupBy: return "group_by";
case FunctionContext::Join: return "join";
case FunctionContext::WindowFunction: return "window";
case FunctionContext::Nested: return "nested";
default: return "unknown";
}
}
struct ParseFunctionsState : public GlobalTableFunctionState {
idx_t row = 0;
vector<FunctionResult> results;
};
struct ParseFunctionsBindData : public TableFunctionData {
string sql;
};
// BIND function: runs during query planning to decide output schema
static unique_ptr<FunctionData> ParseFunctionsBind(ClientContext &context,
TableFunctionBindInput &input,
vector<LogicalType> &return_types,
vector<string> &names) {
string sql_input = StringValue::Get(input.inputs[0]);
// always return the same columns:
return_types = {LogicalType::VARCHAR, LogicalType::VARCHAR, LogicalType::VARCHAR};
// function name, schema name, usage context
names = {"function_name", "schema", "context"};
// create a bind data object to hold the SQL input
auto result = make_uniq<ParseFunctionsBindData>();
result->sql = sql_input;
return std::move(result);
}
// INIT function: runs before table function execution
static unique_ptr<GlobalTableFunctionState> ParseFunctionsInit(ClientContext &context,
TableFunctionInitInput &input) {
return make_uniq<ParseFunctionsState>();
}
class FunctionExtractor {
public:
static void ExtractFromExpression(const ParsedExpression &expr,
std::vector<FunctionResult> &results,
FunctionContext context = FunctionContext::Select) {
if (expr.expression_class == ExpressionClass::FUNCTION) {
auto &func = (FunctionExpression &)expr;
results.push_back(FunctionResult{
func.function_name,
func.schema.empty() ? "main" : func.schema,
ToString(context)
});
// For nested function calls within this function, mark as nested
ParsedExpressionIterator::EnumerateChildren(expr, [&](const ParsedExpression &child) {
ExtractFromExpression(child, results, FunctionContext::Nested);
});
} else if (expr.expression_class == ExpressionClass::WINDOW) {
auto &window_expr = (WindowExpression &)expr;
results.push_back(FunctionResult{
window_expr.function_name,
window_expr.schema.empty() ? "main" : window_expr.schema,
ToString(context)
});
// Extract functions from window function arguments
for (const auto &child : window_expr.children) {
if (child) {
ExtractFromExpression(*child, results, FunctionContext::Nested);
}
}
// Extract functions from PARTITION BY expressions
for (const auto &partition : window_expr.partitions) {
if (partition) {
ExtractFromExpression(*partition, results, FunctionContext::Nested);
}
}
// Extract functions from ORDER BY expressions
for (const auto &order : window_expr.orders) {
if (order.expression) {
ExtractFromExpression(*order.expression, results, FunctionContext::Nested);
}
}
// Extract functions from argument ordering expressions
for (const auto &arg_order : window_expr.arg_orders) {
if (arg_order.expression) {
ExtractFromExpression(*arg_order.expression, results, FunctionContext::Nested);
}
}
// Extract functions from frame expressions
if (window_expr.start_expr) {
ExtractFromExpression(*window_expr.start_expr, results, FunctionContext::Nested);
}
if (window_expr.end_expr) {
ExtractFromExpression(*window_expr.end_expr, results, FunctionContext::Nested);
}
if (window_expr.offset_expr) {
ExtractFromExpression(*window_expr.offset_expr, results, FunctionContext::Nested);
}
if (window_expr.default_expr) {
ExtractFromExpression(*window_expr.default_expr, results, FunctionContext::Nested);
}
// Extract functions from filter expression
if (window_expr.filter_expr) {
ExtractFromExpression(*window_expr.filter_expr, results, FunctionContext::Nested);
}
} else {
// For non-function expressions, preserve the current context
ParsedExpressionIterator::EnumerateChildren(expr, [&](const ParsedExpression &child) {
ExtractFromExpression(child, results, context);
});
}
}
static void ExtractFromExpressionList(const vector<unique_ptr<ParsedExpression>> &expressions,
std::vector<FunctionResult> &results,
FunctionContext context) {
for (const auto &expr : expressions) {
if (expr) {
ExtractFromExpression(*expr, results, context);
}
}
}
};
static void ExtractFunctionsFromQueryNode(const QueryNode &node, std::vector<FunctionResult> &results) {
if (node.type == QueryNodeType::SELECT_NODE) {
auto &select_node = (SelectNode &)node;
// Extract from CTEs first (to match expected order in tests)
for (const auto &cte : select_node.cte_map.map) {
if (cte.second && cte.second->query && cte.second->query->node) {
ExtractFunctionsFromQueryNode(*cte.second->query->node, results);
}
}
// Extract from SELECT list
FunctionExtractor::ExtractFromExpressionList(select_node.select_list, results, FunctionContext::Select);
// Extract from WHERE clause
if (select_node.where_clause) {
FunctionExtractor::ExtractFromExpression(*select_node.where_clause, results, FunctionContext::Where);
}
// Extract from GROUP BY clause
FunctionExtractor::ExtractFromExpressionList(select_node.groups.group_expressions, results, FunctionContext::GroupBy);
// Extract from HAVING clause
if (select_node.having) {
FunctionExtractor::ExtractFromExpression(*select_node.having, results, FunctionContext::Having);
}
// Extract from ORDER BY clause
for (const auto &modifier : select_node.modifiers) {
if (modifier->type == ResultModifierType::ORDER_MODIFIER) {
auto &order_modifier = (OrderModifier &)*modifier;
for (const auto &order : order_modifier.orders) {
if (order.expression) {
FunctionExtractor::ExtractFromExpression(*order.expression, results, FunctionContext::OrderBy);
}
}
}
}
// additional step necessary for duckdb v1.4.0: unwrap CTE node
} else if (node.type == QueryNodeType::CTE_NODE) {
auto &cte_node = (CTENode &)node;
if (cte_node.child) {
ExtractFunctionsFromQueryNode(*cte_node.child, results);
}
}
}
static void ExtractFunctionsFromSQL(const std::string &sql, std::vector<FunctionResult> &results) {
Parser parser;
try {
parser.ParseQuery(sql);
} catch (const ParserException &ex) {
// swallow parser exceptions to make this function more robust. is_parsable can be used if needed
return;
}
for (auto &stmt : parser.statements) {
if (stmt->type == StatementType::SELECT_STATEMENT) {
auto &select_stmt = (SelectStatement &)*stmt;
if (select_stmt.node) {
ExtractFunctionsFromQueryNode(*select_stmt.node, results);
}
}
}
}
static void ParseFunctionsFunction(ClientContext &context,
TableFunctionInput &data,
DataChunk &output) {
auto &state = (ParseFunctionsState &)*data.global_state;
auto &bind_data = (ParseFunctionsBindData &)*data.bind_data;
if (state.results.empty() && state.row == 0) {
ExtractFunctionsFromSQL(bind_data.sql, state.results);
}
if (state.row >= state.results.size()) {
return;
}
auto &func = state.results[state.row];
output.SetCardinality(1);
output.SetValue(0, 0, Value(func.function_name));
output.SetValue(1, 0, Value(func.schema));
output.SetValue(2, 0, Value(func.context));
state.row++;
}
static void ParseFunctionNamesScalarFunction(DataChunk &args, ExpressionState &state, Vector &result) {
UnaryExecutor::Execute<string_t, list_entry_t>(args.data[0], result, args.size(),
[&result](string_t query) -> list_entry_t {
// Parse the SQL query and extract function names
auto query_string = query.GetString();
std::vector<FunctionResult> parsed_functions;
ExtractFunctionsFromSQL(query_string, parsed_functions);
auto current_size = ListVector::GetListSize(result);
auto number_of_functions = parsed_functions.size();
auto new_size = current_size + number_of_functions;
// grow list if needed
if (ListVector::GetListCapacity(result) < new_size) {
ListVector::Reserve(result, new_size);
}
// Write the function names into the child vector
auto functions = FlatVector::GetData<string_t>(ListVector::GetEntry(result));
for (size_t i = 0; i < parsed_functions.size(); i++) {
auto &func = parsed_functions[i];
functions[current_size + i] = StringVector::AddStringOrBlob(ListVector::GetEntry(result), func.function_name);
}
// Update size
ListVector::SetListSize(result, new_size);
return list_entry_t(current_size, number_of_functions);
});
}
static void ParseFunctionsScalarFunction_struct(DataChunk &args, ExpressionState &state, Vector &result) {
UnaryExecutor::Execute<string_t, list_entry_t>(args.data[0], result, args.size(),
[&result](string_t query) -> list_entry_t {
// Parse the SQL query and extract function names
auto query_string = query.GetString();
std::vector<FunctionResult> parsed_functions;
ExtractFunctionsFromSQL(query_string, parsed_functions);
auto current_size = ListVector::GetListSize(result);
auto number_of_functions = parsed_functions.size();
auto new_size = current_size + number_of_functions;
// Grow list vector if needed
if (ListVector::GetListCapacity(result) < new_size) {
ListVector::Reserve(result, new_size);
}
// Get the struct child vector of the list
auto &struct_vector = ListVector::GetEntry(result);
// Ensure list size is updated
ListVector::SetListSize(result, new_size);
// Get the fields in the STRUCT
auto &entries = StructVector::GetEntries(struct_vector);
auto &function_name_entry = *entries[0]; // "function_name" field
auto &schema_entry = *entries[1]; // "schema" field
auto &context_entry = *entries[2]; // "context" field
auto function_name_data = FlatVector::GetData<string_t>(function_name_entry);
auto schema_data = FlatVector::GetData<string_t>(schema_entry);
auto context_data = FlatVector::GetData<string_t>(context_entry);
for (size_t i = 0; i < number_of_functions; i++) {
const auto &func = parsed_functions[i];
auto idx = current_size + i;
function_name_data[idx] = StringVector::AddStringOrBlob(function_name_entry, func.function_name);
schema_data[idx] = StringVector::AddStringOrBlob(schema_entry, func.schema);
context_data[idx] = StringVector::AddStringOrBlob(context_entry, func.context);
}
return list_entry_t(current_size, number_of_functions);
});
}
// Extension scaffolding
// ---------------------------------------------------
void RegisterParseFunctionsFunction(ExtensionLoader &loader) {
TableFunction tf("parse_functions", {LogicalType::VARCHAR}, ParseFunctionsFunction, ParseFunctionsBind, ParseFunctionsInit);
loader.RegisterFunction(tf);
}
void RegisterParseFunctionScalarFunction(ExtensionLoader &loader) {
// parse_function_names is a scalar function that returns a list of function names
ScalarFunction sf("parse_function_names", {LogicalType::VARCHAR}, LogicalType::LIST(LogicalType::VARCHAR), ParseFunctionNamesScalarFunction);
loader.RegisterFunction(sf);
// parse_functions_struct is a scalar function that returns a list of structs
auto return_type = LogicalType::LIST(LogicalType::STRUCT({
{"function_name", LogicalType::VARCHAR},
{"schema", LogicalType::VARCHAR},
{"context", LogicalType::VARCHAR}
}));
ScalarFunction sf_struct("parse_functions", {LogicalType::VARCHAR}, return_type, ParseFunctionsScalarFunction_struct);
loader.RegisterFunction(sf_struct);
}
} // namespace duckdb