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
use super::*;
impl Database {
/// Describe a SELECT's physical execution steps without reading table rows.
/// The result has `step`, `operation`, and `detail` columns. Bounded query
/// callers should use `query_with_limits("EXPLAIN ...", ...)` so the plan
/// reflects bounded execution and join strategy.
pub fn explain(&self, sql: &str) -> Result<QueryResult> {
let statement = parse(sql)?;
match statement {
Statement::Explain { statement } => self.explain_statement(&statement, false),
statement => self.explain_statement(&statement, false),
}
}
pub(super) fn explain_statement(
&self,
statement: &Statement,
_bounded: bool,
) -> Result<QueryResult> {
let mut steps = Vec::<(&str, String)>::new();
let (projection, distinct, filter, group_by, having, order, limit, offset, columns) =
match statement {
Statement::Select {
table,
projection,
distinct,
before,
filter,
group_by,
having,
order,
limit,
offset,
} => {
let columns = self.column_names(table)?;
check_projection(&columns, projection)?;
if let Some(filter) = filter {
check_predicate_columns(&columns, filter)?;
}
let grouped = !group_by.is_empty()
|| projection_has_aggregate(projection)
|| having.is_some();
let count_only = filter.is_none()
&& group_by.is_empty()
&& having.is_none()
&& order.is_empty()
&& limit.is_none()
&& *offset == 0
&& !distinct
&& count_star_only(projection).is_some();
steps.push((
"snapshot",
format!("transaction {}", before.unwrap_or(self.current_tx())),
));
if count_only {
steps.push((
"count envelopes",
format!("{table}: MVCC visibility only; row bodies are not decoded"),
));
return Ok(plan_result(steps));
}
if !grouped
&& filter.is_none()
&& !distinct
&& order.len() == 1
&& self.has_index(table, &order[0].column)
{
project_select(
columns,
Vec::new(),
projection.clone(),
&[],
false,
*limit,
*offset,
)?;
steps.push((
"ordered index scan",
format!(
"{table}.{} {}; early stop {}",
order[0].column,
if order[0].descending { "DESC" } else { "ASC" },
limit
.map(|n| n.saturating_add(*offset).to_string())
.unwrap_or_else(|| "none".into())
),
));
steps.push(("project", "select output columns".into()));
append_limit(&mut steps, *limit, *offset);
return Ok(plan_result(steps));
}
let access = filter
.as_ref()
.and_then(|p| index_access(&self.tables[table], p));
match access {
Some((column, operation)) => steps.push((
operation,
format!("{table}.{column}; recheck full predicate and MVCC visibility"),
)),
None => steps.push((
"table scan",
format!("{table}: scan row versions and check MVCC visibility"),
)),
}
(
projection, distinct, filter, group_by, having, order, limit, offset,
columns,
)
}
Statement::SelectJoin {
source,
joins,
before,
projection,
distinct,
filter,
group_by,
having,
order,
limit,
offset,
} => {
let mut columns = self
.column_names(&source.name)?
.into_iter()
.map(|c| format!("{}.{c}", source.qualifier()))
.collect::<Vec<_>>();
steps.push((
"snapshot",
format!("transaction {}", before.unwrap_or(self.current_tx())),
));
let pushed = filter
.as_ref()
.and_then(|p| source_predicate(p, source.qualifier()));
let access = pushed
.as_ref()
.and_then(|p| index_access(&self.tables[&source.name], p));
steps.push((
access
.map(|(_, operation)| operation)
.unwrap_or("table scan"),
format!("{} AS {}", source.name, source.qualifier()),
));
if pushed.is_some() {
steps.push((
"source filter",
"apply driving-relation predicates before joining".into(),
));
}
for join in joins {
let right = self
.column_names(&join.table.name)?
.into_iter()
.map(|c| format!("{}.{c}", join.table.qualifier()))
.collect::<Vec<_>>();
let (_, right_key) = resolve_join_keys(
&columns,
&right,
&join.first_column,
&join.second_column,
)?;
let right_column = right[right_key]
.rsplit_once('.')
.map(|(_, column)| column)
.unwrap_or(&right[right_key]);
if self.has_index(&join.table.name, right_column) {
steps.push((
if join.left_join {
"adaptive indexed left join"
} else {
"adaptive indexed inner join"
},
format!(
"{} = {}; probe {}.{} once per distinct left key when cheaper, otherwise build the right input",
join.first_column,
join.second_column,
join.table.qualifier(),
right_column
),
));
} else {
steps.push((
"table scan",
format!("{} AS {}", join.table.name, join.table.qualifier()),
));
steps.push((
if join.left_join {
"left equality join"
} else {
"inner equality join"
},
format!(
"{} = {}; build ordered map of right input",
join.first_column, join.second_column
),
));
}
columns.extend(right);
}
if let Some(filter) = filter {
check_predicate_columns(&columns, filter)?;
}
(
projection, distinct, filter, group_by, having, order, limit, offset,
columns,
)
}
_ => return Err(PvError::Query("EXPLAIN requires a SELECT statement".into())),
};
if filter.is_some() {
steps.push(("filter", "evaluate WHERE with SQL NULL semantics".into()));
}
let grouped =
!group_by.is_empty() || projection_has_aggregate(projection) || having.is_some();
check_projection(&columns, projection)?;
if grouped {
project_grouped(
columns,
Vec::new(),
projection_to_items(projection.clone())?,
group_by.clone(),
having.clone(),
order.clone(),
*distinct,
*limit,
*offset,
)?;
steps.push((
"aggregate",
if group_by.is_empty() {
"whole input".into()
} else {
format!("group by {}", group_by.join(", "))
},
));
steps.push(("project", "select group output columns".into()));
if having.is_some() {
steps.push(("having", "filter groups".into()));
}
} else {
project_select(
columns,
Vec::new(),
projection.clone(),
order,
*distinct,
*limit,
*offset,
)?;
}
if !order.is_empty() {
steps.push((
if !grouped && !distinct && limit.is_some() {
"top-N sort"
} else {
"sort"
},
order
.iter()
.map(|o| format!("{} {}", o.column, if o.descending { "DESC" } else { "ASC" }))
.collect::<Vec<_>>()
.join(", "),
));
}
if !grouped {
steps.push(("project", "select output columns".into()));
}
if *distinct {
steps.push(("distinct", "deduplicate output rows".into()));
}
append_limit(&mut steps, *limit, *offset);
Ok(plan_result(steps))
}
}
fn check_projection(columns: &[String], projection: &Projection) -> Result<()> {
match projection {
Projection::All => {}
Projection::Columns(names) => {
for name in names {
projection_col_pos(columns, name)?;
}
}
Projection::Items(items) => {
for item in items {
match &item.expr {
SelectExpr::Column(name) => {
projection_col_pos(columns, name)?;
}
SelectExpr::Aggregate(agg) => {
if let Some(name) = &agg.column {
projection_col_pos(columns, name)?;
}
}
SelectExpr::Scalar(expr) => check_scalar(columns, expr)?,
}
}
}
}
Ok(())
}
fn check_scalar(columns: &[String], expr: &ScalarExpr) -> Result<()> {
match expr {
ScalarExpr::Column(name) => {
projection_col_pos(columns, name)?;
}
ScalarExpr::Literal(_) => {}
ScalarExpr::Function { arguments, .. } => {
for arg in arguments {
check_scalar(columns, arg)?;
}
}
ScalarExpr::Case {
branches,
else_expr,
} => {
for (predicate, expr) in branches {
check_predicate_columns(columns, predicate)?;
check_scalar(columns, expr)?;
}
if let Some(expr) = else_expr {
check_scalar(columns, expr)?;
}
}
}
Ok(())
}
fn append_limit(steps: &mut Vec<(&'static str, String)>, limit: Option<usize>, offset: usize) {
if offset > 0 {
steps.push(("offset", offset.to_string()));
}
if let Some(limit) = limit {
steps.push(("limit", limit.to_string()));
}
}
fn plan_result(steps: Vec<(&str, String)>) -> QueryResult {
QueryResult::Rows {
columns: vec!["step".into(), "operation".into(), "detail".into()],
rows: steps
.into_iter()
.enumerate()
.map(|(i, (op, detail))| {
vec![
Value::Int(i as i64),
Value::Text(op.into()),
Value::Text(detail),
]
})
.collect(),
}
}
fn index_access<'a>(table: &'a Table, pred: &'a Predicate) -> Option<(&'a str, &'static str)> {
match pred {
Predicate::Compare { column, op, .. } if table.indexes.contains_key(column) => match op {
CompareOp::Eq => Some((column, "index lookup")),
CompareOp::Lt | CompareOp::Le | CompareOp::Gt | CompareOp::Ge => {
Some((column, "index range scan"))
}
_ => None,
},
Predicate::And(a, b) => index_access(table, a).or_else(|| index_access(table, b)),
Predicate::Between {
column,
negated: false,
..
} if table.indexes.contains_key(column) => Some((column, "index range scan")),
_ => None,
}
}