-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
bind_select_node.cpp
378 lines (352 loc) · 15.7 KB
/
bind_select_node.cpp
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
#include "duckdb/common/limits.hpp"
#include "duckdb/common/string_util.hpp"
#include "duckdb/execution/expression_executor.hpp"
#include "duckdb/main/config.hpp"
#include "duckdb/parser/expression/columnref_expression.hpp"
#include "duckdb/parser/expression/comparison_expression.hpp"
#include "duckdb/parser/expression/constant_expression.hpp"
#include "duckdb/parser/expression/subquery_expression.hpp"
#include "duckdb/parser/query_node/select_node.hpp"
#include "duckdb/parser/tableref/joinref.hpp"
#include "duckdb/planner/binder.hpp"
#include "duckdb/planner/expression_binder/column_alias_binder.hpp"
#include "duckdb/planner/expression_binder/constant_binder.hpp"
#include "duckdb/planner/expression_binder/group_binder.hpp"
#include "duckdb/planner/expression_binder/having_binder.hpp"
#include "duckdb/planner/expression_binder/qualify_binder.hpp"
#include "duckdb/planner/expression_binder/order_binder.hpp"
#include "duckdb/planner/expression_binder/select_binder.hpp"
#include "duckdb/planner/expression_binder/where_binder.hpp"
#include "duckdb/planner/query_node/bound_select_node.hpp"
#include "duckdb/planner/expression_binder/aggregate_binder.hpp"
namespace duckdb {
unique_ptr<Expression> Binder::BindOrderExpression(OrderBinder &order_binder, unique_ptr<ParsedExpression> expr) {
// we treat the Distinct list as a order by
auto bound_expr = order_binder.Bind(move(expr));
if (!bound_expr) {
// DISTINCT ON non-integer constant
// remove the expression from the DISTINCT ON list
return nullptr;
}
D_ASSERT(bound_expr->type == ExpressionType::BOUND_COLUMN_REF);
return bound_expr;
}
unique_ptr<Expression> Binder::BindDelimiter(ClientContext &context, unique_ptr<ParsedExpression> delimiter,
const LogicalType &type, Value &delimiter_value) {
auto new_binder = Binder::CreateBinder(context, this, true);
ExpressionBinder expr_binder(*new_binder, context);
expr_binder.target_type = type;
auto expr = expr_binder.Bind(delimiter);
if (expr->IsFoldable()) {
//! this is a constant
delimiter_value = ExpressionExecutor::EvaluateScalar(*expr).CastAs(type);
return nullptr;
}
return expr;
}
unique_ptr<BoundResultModifier> Binder::BindLimit(LimitModifier &limit_mod) {
auto result = make_unique<BoundLimitModifier>();
if (limit_mod.limit) {
Value val;
result->limit = BindDelimiter(context, move(limit_mod.limit), LogicalType::BIGINT, val);
if (!result->limit) {
result->limit_val = val.GetValue<int64_t>();
}
}
if (limit_mod.offset) {
Value val;
result->offset = BindDelimiter(context, move(limit_mod.offset), LogicalType::BIGINT, val);
if (!result->offset) {
result->offset_val = val.GetValue<int64_t>();
}
}
return move(result);
}
unique_ptr<BoundResultModifier> Binder::BindLimitPercent(LimitPercentModifier &limit_mod) {
auto result = make_unique<BoundLimitPercentModifier>();
if (limit_mod.limit) {
Value val;
result->limit = BindDelimiter(context, move(limit_mod.limit), LogicalType::DOUBLE, val);
if (!result->limit) {
result->limit_percent = val.GetValue<double>();
if (result->limit_percent < 0.0) {
throw Exception("Limit percentage can't be negative value");
}
}
}
if (limit_mod.offset) {
Value val;
result->offset = BindDelimiter(context, move(limit_mod.offset), LogicalType::BIGINT, val);
if (!result->offset) {
result->offset_val = val.GetValue<int64_t>();
}
}
return move(result);
}
void Binder::BindModifiers(OrderBinder &order_binder, QueryNode &statement, BoundQueryNode &result) {
for (auto &mod : statement.modifiers) {
unique_ptr<BoundResultModifier> bound_modifier;
switch (mod->type) {
case ResultModifierType::DISTINCT_MODIFIER: {
auto &distinct = (DistinctModifier &)*mod;
auto bound_distinct = make_unique<BoundDistinctModifier>();
if (distinct.distinct_on_targets.empty()) {
for (idx_t i = 0; i < result.names.size(); i++) {
distinct.distinct_on_targets.push_back(make_unique<ConstantExpression>(Value::INTEGER(1 + i)));
}
}
for (auto &distinct_on_target : distinct.distinct_on_targets) {
auto expr = BindOrderExpression(order_binder, move(distinct_on_target));
if (!expr) {
continue;
}
bound_distinct->target_distincts.push_back(move(expr));
}
bound_modifier = move(bound_distinct);
break;
}
case ResultModifierType::ORDER_MODIFIER: {
auto &order = (OrderModifier &)*mod;
auto bound_order = make_unique<BoundOrderModifier>();
auto &config = DBConfig::GetConfig(context);
for (auto &order_node : order.orders) {
auto order_expression = BindOrderExpression(order_binder, move(order_node.expression));
if (!order_expression) {
continue;
}
auto type = order_node.type == OrderType::ORDER_DEFAULT ? config.default_order_type : order_node.type;
auto null_order = order_node.null_order == OrderByNullType::ORDER_DEFAULT ? config.default_null_order
: order_node.null_order;
bound_order->orders.emplace_back(type, null_order, move(order_expression));
}
if (!bound_order->orders.empty()) {
bound_modifier = move(bound_order);
}
break;
}
case ResultModifierType::LIMIT_MODIFIER:
bound_modifier = BindLimit((LimitModifier &)*mod);
break;
case ResultModifierType::LIMIT_PERCENT_MODIFIER:
bound_modifier = BindLimitPercent((LimitPercentModifier &)*mod);
break;
default:
throw Exception("Unsupported result modifier");
}
if (bound_modifier) {
result.modifiers.push_back(move(bound_modifier));
}
}
}
void Binder::BindModifierTypes(BoundQueryNode &result, const vector<LogicalType> &sql_types, idx_t projection_index) {
for (auto &bound_mod : result.modifiers) {
switch (bound_mod->type) {
case ResultModifierType::DISTINCT_MODIFIER: {
auto &distinct = (BoundDistinctModifier &)*bound_mod;
if (distinct.target_distincts.empty()) {
// DISTINCT without a target: push references to the standard select list
for (idx_t i = 0; i < sql_types.size(); i++) {
distinct.target_distincts.push_back(
make_unique<BoundColumnRefExpression>(sql_types[i], ColumnBinding(projection_index, i)));
}
} else {
// DISTINCT with target list: set types
for (auto &expr : distinct.target_distincts) {
D_ASSERT(expr->type == ExpressionType::BOUND_COLUMN_REF);
auto &bound_colref = (BoundColumnRefExpression &)*expr;
if (bound_colref.binding.column_index == DConstants::INVALID_INDEX) {
throw BinderException("Ambiguous name in DISTINCT ON!");
}
D_ASSERT(bound_colref.binding.column_index < sql_types.size());
bound_colref.return_type = sql_types[bound_colref.binding.column_index];
}
}
for (auto &target_distinct : distinct.target_distincts) {
auto &bound_colref = (BoundColumnRefExpression &)*target_distinct;
auto sql_type = sql_types[bound_colref.binding.column_index];
if (sql_type.id() == LogicalTypeId::VARCHAR) {
target_distinct = ExpressionBinder::PushCollation(context, move(target_distinct),
StringType::GetCollation(sql_type), true);
}
}
break;
}
case ResultModifierType::ORDER_MODIFIER: {
auto &order = (BoundOrderModifier &)*bound_mod;
for (auto &order_node : order.orders) {
auto &expr = order_node.expression;
D_ASSERT(expr->type == ExpressionType::BOUND_COLUMN_REF);
auto &bound_colref = (BoundColumnRefExpression &)*expr;
if (bound_colref.binding.column_index == DConstants::INVALID_INDEX) {
throw BinderException("Ambiguous name in ORDER BY!");
}
D_ASSERT(bound_colref.binding.column_index < sql_types.size());
auto sql_type = sql_types[bound_colref.binding.column_index];
bound_colref.return_type = sql_types[bound_colref.binding.column_index];
if (sql_type.id() == LogicalTypeId::VARCHAR) {
order_node.expression = ExpressionBinder::PushCollation(context, move(order_node.expression),
StringType::GetCollation(sql_type));
}
}
break;
}
default:
break;
}
}
}
unique_ptr<BoundQueryNode> Binder::BindNode(SelectNode &statement) {
auto result = make_unique<BoundSelectNode>();
result->projection_index = GenerateTableIndex();
result->group_index = GenerateTableIndex();
result->aggregate_index = GenerateTableIndex();
result->groupings_index = GenerateTableIndex();
result->window_index = GenerateTableIndex();
result->unnest_index = GenerateTableIndex();
result->prune_index = GenerateTableIndex();
// first bind the FROM table statement
result->from_table = Bind(*statement.from_table);
// bind the sample clause
if (statement.sample) {
result->sample_options = move(statement.sample);
}
// visit the select list and expand any "*" statements
vector<unique_ptr<ParsedExpression>> new_select_list;
for (auto &select_element : statement.select_list) {
if (select_element->GetExpressionType() == ExpressionType::STAR) {
// * statement, expand to all columns from the FROM clause
bind_context.GenerateAllColumnExpressions((StarExpression &)*select_element, new_select_list);
} else {
// regular statement, add it to the list
new_select_list.push_back(move(select_element));
}
}
if (new_select_list.empty()) {
throw BinderException("SELECT list is empty after resolving * expressions!");
}
statement.select_list = move(new_select_list);
// create a mapping of (alias -> index) and a mapping of (Expression -> index) for the SELECT list
unordered_map<string, idx_t> alias_map;
expression_map_t<idx_t> projection_map;
for (idx_t i = 0; i < statement.select_list.size(); i++) {
auto &expr = statement.select_list[i];
result->names.push_back(expr->GetName());
ExpressionBinder::QualifyColumnNames(*this, expr);
if (!expr->alias.empty()) {
alias_map[expr->alias] = i;
result->names[i] = expr->alias;
}
projection_map[expr.get()] = i;
result->original_expressions.push_back(expr->Copy());
}
result->column_count = statement.select_list.size();
// first visit the WHERE clause
// the WHERE clause happens before the GROUP BY, PROJECTION or HAVING clauses
if (statement.where_clause) {
ColumnAliasBinder alias_binder(*result, alias_map);
WhereBinder where_binder(*this, context, &alias_binder);
unique_ptr<ParsedExpression> condition = move(statement.where_clause);
result->where_clause = where_binder.Bind(condition);
}
// now bind all the result modifiers; including DISTINCT and ORDER BY targets
OrderBinder order_binder({this}, result->projection_index, statement, alias_map, projection_map);
BindModifiers(order_binder, statement, *result);
vector<unique_ptr<ParsedExpression>> unbound_groups;
BoundGroupInformation info;
auto &group_expressions = statement.groups.group_expressions;
if (!group_expressions.empty()) {
// the statement has a GROUP BY clause, bind it
unbound_groups.resize(group_expressions.size());
GroupBinder group_binder(*this, context, statement, result->group_index, alias_map, info.alias_map);
for (idx_t i = 0; i < group_expressions.size(); i++) {
// we keep a copy of the unbound expression;
// we keep the unbound copy around to check for group references in the SELECT and HAVING clause
// the reason we want the unbound copy is because we want to figure out whether an expression
// is a group reference BEFORE binding in the SELECT/HAVING binder
group_binder.unbound_expression = group_expressions[i]->Copy();
group_binder.bind_index = i;
// bind the groups
LogicalType group_type;
auto bound_expr = group_binder.Bind(group_expressions[i], &group_type);
D_ASSERT(bound_expr->return_type.id() != LogicalTypeId::INVALID);
// push a potential collation, if necessary
bound_expr =
ExpressionBinder::PushCollation(context, move(bound_expr), StringType::GetCollation(group_type), true);
result->groups.group_expressions.push_back(move(bound_expr));
// in the unbound expression we DO bind the table names of any ColumnRefs
// we do this to make sure that "table.a" and "a" are treated the same
// if we wouldn't do this then (SELECT test.a FROM test GROUP BY a) would not work because "test.a" <> "a"
// hence we convert "a" -> "test.a" in the unbound expression
unbound_groups[i] = move(group_binder.unbound_expression);
ExpressionBinder::QualifyColumnNames(*this, unbound_groups[i]);
info.map[unbound_groups[i].get()] = i;
}
}
result->groups.grouping_sets = move(statement.groups.grouping_sets);
// bind the HAVING clause, if any
if (statement.having) {
HavingBinder having_binder(*this, context, *result, info, alias_map);
ExpressionBinder::QualifyColumnNames(*this, statement.having);
result->having = having_binder.Bind(statement.having);
}
// bind the QUALIFY clause, if any
if (statement.qualify) {
QualifyBinder qualify_binder(*this, context, *result, info, alias_map);
ExpressionBinder::QualifyColumnNames(*this, statement.qualify);
result->qualify = qualify_binder.Bind(statement.qualify);
}
// after that, we bind to the SELECT list
SelectBinder select_binder(*this, context, *result, info);
vector<LogicalType> internal_sql_types;
for (idx_t i = 0; i < statement.select_list.size(); i++) {
LogicalType result_type;
auto expr = select_binder.Bind(statement.select_list[i], &result_type);
if (statement.aggregate_handling == AggregateHandling::FORCE_AGGREGATES && select_binder.HasBoundColumns()) {
if (select_binder.BoundAggregates()) {
throw BinderException("Cannot mix aggregates with non-aggregated columns!");
}
// we are forcing aggregates, and the node has columns bound
// this entry becomes a group
auto group_ref = make_unique<BoundColumnRefExpression>(
expr->return_type, ColumnBinding(result->group_index, result->groups.group_expressions.size()));
result->groups.group_expressions.push_back(move(expr));
expr = move(group_ref);
}
result->select_list.push_back(move(expr));
if (i < result->column_count) {
result->types.push_back(result_type);
}
internal_sql_types.push_back(result_type);
if (statement.aggregate_handling == AggregateHandling::FORCE_AGGREGATES) {
select_binder.ResetBindings();
}
}
result->need_prune = result->select_list.size() > result->column_count;
// in the normal select binder, we bind columns as if there is no aggregation
// i.e. in the query [SELECT i, SUM(i) FROM integers;] the "i" will be bound as a normal column
// since we have an aggregation, we need to either (1) throw an error, or (2) wrap the column in a FIRST() aggregate
// we choose the former one [CONTROVERSIAL: this is the PostgreSQL behavior]
if (!result->groups.group_expressions.empty() || !result->aggregates.empty() || statement.having ||
!result->groups.grouping_sets.empty()) {
if (statement.aggregate_handling == AggregateHandling::NO_AGGREGATES_ALLOWED) {
throw BinderException("Aggregates cannot be present in a Project relation!");
} else if (statement.aggregate_handling == AggregateHandling::STANDARD_HANDLING) {
if (select_binder.HasBoundColumns()) {
auto &bound_columns = select_binder.GetBoundColumns();
throw BinderException(
FormatError(bound_columns[0].query_location,
"column \"%s\" must appear in the GROUP BY clause or be used in an aggregate function",
bound_columns[0].name));
}
}
}
// QUALIFY clause requires at least one window function to be specified in at least one of the SELECT column list or
// the filter predicate of the QUALIFY clause
if (statement.qualify && result->windows.empty()) {
throw BinderException("at least one window function must appear in the SELECT column or QUALIFY clause");
}
// now that the SELECT list is bound, we set the types of DISTINCT/ORDER BY expressions
BindModifierTypes(*result, internal_sql_types, result->projection_index);
return move(result);
}
} // namespace duckdb