Repository navigation
Expand file tree
/
Copy pathquery_plan.cpp
More file actions
489 lines (470 loc) · 18.8 KB
/
Copy pathquery_plan.cpp
File metadata and controls
489 lines (470 loc) · 18.8 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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#include <teaql/sql/detail/query_plan.hpp>
#include <teaql/sql/detail/having.hpp>
#include <teaql/sql/detail/statistical.hpp>
namespace teaql::detail {
std::optional<String> normalize_exact_decimal_aggregates(Memory memory,
const EntityDescriptor& entity,
const SelectQuery& query,
std::span<CompactRow> rows) {
const auto normalize_alias = [&](std::string_view alias) -> std::optional<String> {
for (auto& row : rows) {
auto* value = row.get_mut(alias);
if (!value) {
return String("exact Decimal aggregate alias is missing", memory);
}
if (value->is_null() || std::holds_alternative<Decimal>(value->data)) {
continue;
}
if (std::holds_alternative<String>(value->data) ||
std::holds_alternative<std::int64_t>(value->data) ||
std::holds_alternative<std::uint64_t>(value->data)) {
const auto parsed = value->try_decimal();
if (!parsed) {
return String("exact Decimal aggregate value is invalid", memory);
}
*value = Value(memory, *parsed);
} else {
return String("exact Decimal aggregate returned an inexact type", memory);
}
}
return {};
};
const auto decimal_field = [&](std::string_view field) {
const auto* property = entity.property_by_name(field);
return property && property->data_type == DataType::Decimal;
};
for (const auto& aggregate : query.aggregates) {
if ((aggregate.function == AggregateFunction::Sum ||
aggregate.function == AggregateFunction::Avg ||
aggregate.function == AggregateFunction::Min ||
aggregate.function == AggregateFunction::Max) &&
decimal_field(aggregate.field)) {
if (auto error = normalize_alias(aggregate.alias)) {
return error;
}
}
}
for (const auto& projection : query.expr_projection) {
const auto& expression = projection.expr;
if (expression.kind == Expr::Kind::Function &&
(expression.function_kind == ExprFunction::Sum ||
expression.function_kind == ExprFunction::Avg ||
expression.function_kind == ExprFunction::Min ||
expression.function_kind == ExprFunction::Max) &&
expression.args.size() == 1 && expression.args[0].kind == Expr::Kind::Column &&
decimal_field(expression.args[0].name)) {
if (auto error = normalize_alias(projection.alias)) {
return error;
}
}
}
return {};
}
namespace {
[[noreturn]] void statistical_error(Memory memory, std::string_view message) {
throw SqlCompileError(std::allocator_arg,
Allocator(memory),
SqlCompileError::Code::InvalidFunctionArguments,
message);
}
CompilationMetadata
statistical_metadata(Memory memory, const SchemaProvider& schema, const SelectQuery& query) {
auto graph = statistical_query_graph(memory, query);
if (!graph) {
statistical_error(memory, graph.error().message);
}
CompilationMetadata metadata(std::allocator_arg, Allocator(memory));
std::optional<String> source_route;
for (const auto* request : graph.value()) {
const auto* descriptor = schema.get_entity(request->entity);
if (!descriptor) {
throw SqlCompileError(std::allocator_arg,
Allocator(memory),
SqlCompileError::Code::UnknownEntity,
request->entity);
}
const std::string_view route =
descriptor->data_service && !descriptor->data_service->empty()
? std::string_view(*descriptor->data_service)
: std::string_view("default");
if (source_route && *source_route != route) {
statistical_error(memory, "statistical SQL populations must use the same data service");
}
if (!source_route) {
source_route.emplace(route, memory);
}
if (!metadata.find(request->entity)) {
metadata.descriptors.emplace_back(*descriptor);
}
}
return metadata;
}
bool expr_matches(const Expr& a, const Expr& b) {
if (a.kind != b.kind) {
return false;
}
if (a.kind == Expr::Kind::Column) {
return a.name == b.name;
}
if (a.kind == Expr::Kind::LikePattern) {
return true;
}
if (a.kind == Expr::Kind::Value) {
auto* x = a.literal.as_list();
auto* y = b.literal.as_list();
return x && y ? x->size() == y->size() : !x && !y;
}
if (a.kind == Expr::Kind::Function && a.function_kind != b.function_kind) {
return false;
}
if ((a.kind == Expr::Kind::Binary || a.kind == Expr::Kind::SubQuery) && a.op != b.op) {
return false;
}
if (a.args.size() != b.args.size()) {
return false;
}
for (std::size_t i = 0; i < a.args.size(); ++i) {
if (!expr_matches(a.args[i], b.args[i])) {
return false;
}
}
return a.kind != Expr::Kind::SubQuery ||
(a.subquery_data->entity == b.subquery_data->entity &&
select_plan_matches(a.subquery_data->query, b.subquery_data->query));
}
bool optional_matches(const std::optional<Expr>& a, const std::optional<Expr>& b) {
return a && b ? expr_matches(*a, *b) : !a && !b;
}
void normalize(Expr& expr) {
auto r = expr.memory_resource();
if (expr.kind == Expr::Kind::LikePattern) {
expr.name.clear();
expr.literal = Value(r, "");
return;
}
if (expr.kind == Expr::Kind::Value) {
if (auto* values = std::get_if<Value::List>(&expr.literal.data)) {
for (auto& v : *values) {
v = Value(r);
}
} else {
expr.literal = Value(r);
}
return;
}
for (auto& arg : expr.args) {
normalize(arg);
}
if (expr.kind == Expr::Kind::SubQuery) {
expr.subquery_data->query = select_plan_key(r, expr.subquery_data->query);
}
}
void collect_expr(Memory r, const Expr& expr, SqlBindings& params, bool array) {
using K = Expr::Kind;
if (expr.kind == K::Column) {
return;
}
if (expr.kind == K::Value || expr.kind == K::LikePattern) {
params.push(expr.literal);
return;
}
if (expr.kind == K::SubQuery) {
collect_expr(r, expr.args.at(0), params, array);
auto nested = collect_select_bindings(
r, expr.subquery_data->entity, expr.subquery_data->query, array);
params.append_bindings(nested);
return;
}
if (expr.kind == K::Binary) {
collect_expr(r, expr.args.at(0), params, array);
if (auto operand = expr.lowered_like_operand()) {
params.push_like_pattern(operand->first, operand->second);
return;
}
const auto& right = expr.args.at(1);
auto* list = right.kind == K::Value ? right.literal.as_list() : nullptr;
bool in = expr.op == BinaryOp::In || expr.op == BinaryOp::NotIn ||
expr.op == BinaryOp::InLarge || expr.op == BinaryOp::NotInLarge;
if (list && in) {
if (array && (expr.op == BinaryOp::InLarge || expr.op == BinaryOp::NotInLarge)) {
params.push(right.literal);
} else {
for (const auto& v : *list) {
params.push(v);
}
}
} else {
collect_expr(r, right, params, array);
}
return;
}
for (const auto& arg : expr.args) {
collect_expr(r, arg, params, array);
}
}
const Expr* partition_predicate(const Expr& expr, std::string_view field) {
if (expr.kind == Expr::Kind::Binary &&
(expr.op == BinaryOp::In || expr.op == BinaryOp::InLarge) &&
expr.args.at(0).kind == Expr::Kind::Column && expr.args[0].name == field) {
return &expr;
}
if (expr.kind == Expr::Kind::And) {
for (const auto& arg : expr.args) {
if (auto* found = partition_predicate(arg, field)) {
return found;
}
}
}
return nullptr;
}
}
bool select_plan_matches(const SelectQuery& a, const SelectQuery& b) {
if (bool(a.dynamic_property_definitions) != bool(b.dynamic_property_definitions) ||
(a.dynamic_property_definitions &&
*a.dynamic_property_definitions != *b.dynamic_property_definitions)) {
return false;
}
if (a.hard_limit_value != b.hard_limit_value || a.entity != b.entity ||
a.projection != b.projection || a.expr_projection.size() != b.expr_projection.size() ||
a.search_text.has_value() != b.search_text.has_value() ||
!optional_matches(a.predicate, b.predicate) ||
!optional_matches(a.having_predicate, b.having_predicate) ||
a.order_by.size() != b.order_by.size()) {
return false;
}
for (std::size_t i = 0; i < a.expr_projection.size(); ++i) {
if (a.expr_projection[i].alias != b.expr_projection[i].alias ||
!expr_matches(a.expr_projection[i].expr, b.expr_projection[i].expr)) {
return false;
}
}
for (std::size_t i = 0; i < a.order_by.size(); ++i) {
if (a.order_by[i].field != b.order_by[i].field ||
a.order_by[i].direction != b.order_by[i].direction ||
!optional_matches(a.order_by[i].expr, b.order_by[i].expr)) {
return false;
}
}
// Deliberately omit comment/trace, probe threshold and id-set pagination,
// exactly as the fixed source's plan matcher does.
return a.slice == b.slice && a.partition_field == b.partition_field &&
a.aggregates == b.aggregates && a.group_by_fields == b.group_by_fields &&
a.relations == b.relations && a.aggregation_cache == b.aggregation_cache &&
a.raw_sql_text == b.raw_sql_text &&
a.raw_sql_search_criteria == b.raw_sql_search_criteria &&
a.dynamic_properties == b.dynamic_properties && a.raw_projections == b.raw_projections &&
a.object_group_bys == b.object_group_bys &&
a.child_enhancements == b.child_enhancements && a.stream_config == b.stream_config &&
a.continuous_page_fetch == b.continuous_page_fetch;
}
SelectQuery select_plan_key(Memory r, const SelectQuery& query) {
// Strip execution headers before copying the normalized shape into a
// longer-lived cache. Context-owned header payloads cannot be reclaimed
// individually after an accidental destination copy.
auto key = query.clone(query.memory_resource());
key.clear_request_scope();
key.comment_text.reset();
key.trace_chain.clear();
if (key.search_text) {
key.search_text->clear();
}
for (auto& p : key.expr_projection) {
normalize(p.expr);
}
if (key.predicate) {
normalize(*key.predicate);
}
if (key.having_predicate) {
normalize(*key.having_predicate);
}
for (auto& order : key.order_by) {
if (order.expr) {
normalize(*order.expr);
}
}
return key.memory_resource() == r ? std::move(key) : key.clone(r);
}
SqlBindings collect_select_bindings(Memory r,
const EntityDescriptor& entity,
const SelectQuery& query,
bool array) {
SqlBindings params(r);
params.capture_query_scope(query);
if (query.raw_sql_text) {
return params;
}
for (const auto& p : query.expr_projection) {
collect_expr(r, p.expr, params, array);
}
bool partitioned = query.partition_field && query.slice;
if (partitioned) {
for (const auto& order : query.order_by) {
if (order.expr) {
collect_expr(r, *order.expr, params, array);
}
}
}
if (query.predicate) {
collect_expr(r, *query.predicate, params, array);
}
if (query.search_text) {
String pattern("%", r);
pattern += *query.search_text;
pattern += '%';
for (const auto& p : entity.properties) {
if (p.data_type == DataType::Text || p.data_type == DataType::LargeText) {
params.push(Value(r, pattern));
}
}
}
if (query.having_predicate) {
collect_expr(r, *query.having_predicate, params, array);
}
if (partitioned) {
return params;
}
for (const auto& order : query.order_by) {
if (order.expr) {
collect_expr(r, *order.expr, params, array);
}
}
return params;
}
Vector<Value> collect_select_params(Memory r,
const EntityDescriptor& entity,
const SelectQuery& query,
bool array) {
auto bindings = collect_select_bindings(r, entity, query, array);
return std::move(bindings).into_values();
}
const Value::List* partition_probe_values(const SelectQuery& query) {
if (!query.partition_field || !query.predicate) {
return nullptr;
}
auto find = [&](auto&& self, const Expr& expr) -> const Value::List* {
if (expr.kind == Expr::Kind::Binary &&
(expr.op == BinaryOp::In || expr.op == BinaryOp::InLarge) &&
expr.args.at(0).kind == Expr::Kind::Column &&
expr.args[0].name == *query.partition_field) {
return expr.args.at(1).kind == Expr::Kind::Value ? expr.args[1].literal.as_list()
: nullptr;
}
if (expr.kind == Expr::Kind::And) {
for (const auto& arg : expr.args) {
if (auto* values = self(self, arg)) {
return values;
}
}
}
return nullptr;
};
return find(find, *query.predicate);
}
std::optional<SelectQuery>
scalar_partition_probe_query(Memory r, const SelectQuery& query, const Value& value) {
if (!query.partition_field || !query.predicate) {
return {};
}
auto scalar = query.clone(r);
auto* found =
const_cast<Expr*>(partition_predicate(*scalar.predicate, *scalar.partition_field));
if (!found) {
return {};
}
found->op = BinaryOp::Eq;
found->args.at(1) = Expr::value(r, value);
scalar.partition_field.reset();
return scalar;
}
const EntityDescriptor* SqlExecutorState::entity_descriptor(const SchemaProvider& provider,
std::string_view name) const {
auto found = descriptors_.find(name);
if (found != descriptors_.end()) {
return &found->second;
}
auto* descriptor = provider.get_entity(name);
if (!descriptor) {
return nullptr;
}
return &descriptors_.emplace(String(name, memory_resource()), *descriptor).first->second;
}
std::pair<ScopedBox<StatisticalPlan>, CompiledQuery>
SqlExecutorState::compile_select_for_execution(Memory memory,
const SqlDialect& dialect,
const SchemaProvider& schema,
const EntityDescriptor& entity,
const SelectQuery& query) const {
if (query.requires_statistical_plan()) {
auto metadata = statistical_metadata(memory, schema, query);
auto logical = StatisticalPlan::build(memory, query, [&](std::string_view name) {
return metadata.find(name);
});
if (!logical) {
statistical_error(memory, logical.error().message);
}
auto plan = make_box<StatisticalPlan>(memory, std::move(logical).value());
auto compiled = compile_statistical_plan_with_metadata(memory, dialect, *plan, metadata);
return {std::move(plan), std::move(compiled)};
}
auto nested = has_nested_statistics(memory, query);
if (!nested) {
statistical_error(memory, nested.error().message);
}
if (nested.value()) {
auto metadata = statistical_metadata(memory, schema, query);
SqlBindings bindings(memory);
SqlCompilationMetadataScope scope(bindings, metadata);
CompiledQuery compiled(std::allocator_arg, Allocator(memory));
compiled.sql = dialect.compile_select_sql(memory, entity, query, bindings);
compiled.log_context = bindings.log_context(memory, dialect.kind());
compiled.params = std::move(bindings).into_values();
compiled.comment = clone_in(memory, query.comment_text);
return {nullptr, std::move(compiled)};
}
return {nullptr, compile_select_cached(memory, dialect, entity, query)};
}
CompiledQuery SqlExecutorState::compile_select_cached(Memory memory,
const SqlDialect& dialect,
const SchemaProvider& schema,
const EntityDescriptor& entity,
const SelectQuery& query) const {
return compile_select_for_execution(memory, dialect, schema, entity, query).second;
}
CompiledQuery SqlExecutorState::compile_select_cached(Memory r,
const SqlDialect& dialect,
const EntityDescriptor& entity,
const SelectQuery& query) const {
if (requires_fresh_compilation(r, query)) {
return dialect.compile_select(r, entity, query);
}
for (const auto& plan : plans_) {
if (plan->descriptor == entity && select_plan_matches(plan->key, query)) {
CompiledQuery out(std::allocator_arg, Allocator(r));
auto bindings =
collect_select_bindings(r, entity, query, dialect.large_in_uses_array_param());
out.log_context = bindings.rebind_log_context(r, plan->log);
out.sql = plan->sql;
out.params = std::move(bindings).into_values();
out.comment = clone_in(r, query.comment_text);
return out;
}
}
auto key = select_plan_key(memory_resource(), query);
auto result = dialect.compile_select(r, entity, query);
if (plans_.size() >= 256) {
plans_.erase(plans_.begin());
}
bool exists = false;
for (const auto& plan : plans_) {
if (plan->descriptor == entity && select_plan_matches(plan->key, query)) {
exists = true;
break;
}
}
if (!exists) {
plans_.emplace_back(
make_box<CachedSelectPlan>(memory_resource(), entity, std::move(key), result));
}
return result;
}
}