Repository navigation
Expand file tree
/
Copy pathexecute.rs
More file actions
276 lines (253 loc) · 9.29 KB
/
Copy pathexecute.rs
File metadata and controls
276 lines (253 loc) · 9.29 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
use datafusion::{
arrow::{
array::RecordBatch,
error::ArrowError,
json::{writer::JsonArray, WriterBuilder},
},
common::tree_node::TreeNode,
dataframe::DataFrame,
error::DataFusionError,
};
use engine_types::HttpContext;
use hasura_authn_core::Session;
use metadata_resolve as resolved;
use planner::{
command::{NDCFunctionPushDown, NDCProcedurePushDown},
common::PhysicalPlanOptions,
model::{NDCAggregatePushdown, NDCQueryPushDown},
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use thiserror::Error;
use tracing_util::{
set_attribute_on_active_span, ErrorVisibility, SpanVisibility, Successful, TraceableError,
};
pub use datafusion::execution::context::SessionContext;
pub(crate) mod optimizer;
pub(crate) mod planner;
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SqlRequest {
pub sql: String,
#[serde(default)]
pub disallow_mutations: bool,
}
impl SqlRequest {
pub fn new(sql: String) -> Self {
SqlRequest {
sql,
disallow_mutations: false,
}
}
}
#[derive(Error, Debug)]
pub enum SqlExecutionError {
#[error("error in data fusion: {0}")]
DataFusion(#[from] DataFusionError),
#[error("error in encoding data: {0}")]
Arrow(String),
}
impl SqlExecutionError {
pub fn to_error_response(&self) -> serde_json::Value {
let message = self.to_string();
let detail = match self {
SqlExecutionError::DataFusion(DataFusionError::External(e)) => {
use planner::command::physical::procedure::ExecutionPlanError;
if let Some(ExecutionPlanError::MutationsAreDisallowed(command_target)) =
e.downcast_ref::<ExecutionPlanError>()
{
serde_json::to_value(command_target).unwrap_or(serde_json::Value::Null)
} else {
serde_json::Value::Null
}
}
_ => serde_json::Value::Null,
};
if detail == serde_json::Value::Null {
serde_json::json!({"error": message})
} else {
serde_json::json!({"error": message, "detail": detail})
}
}
}
impl From<ArrowError> for SqlExecutionError {
fn from(e: ArrowError) -> Self {
Self::Arrow(e.to_string())
}
}
impl TraceableError for SqlExecutionError {
fn visibility(&self) -> ErrorVisibility {
ErrorVisibility::User
}
}
/// Executes an SQL Request using the Apache DataFusion query engine.
pub async fn execute_sql(
request_headers: Arc<reqwest::header::HeaderMap>,
catalog: Arc<crate::catalog::Catalog>,
metadata: Arc<resolved::Metadata>,
session: Arc<Session>,
http_context: Arc<HttpContext>,
request: &SqlRequest,
) -> Result<Vec<u8>, SqlExecutionError> {
let tracer = tracing_util::global_tracer();
let session_context = tracer
.in_span(
"create_session_context",
"Create a datafusion SessionContext",
SpanVisibility::Internal,
|| {
let session = catalog.create_session_context(
metadata,
&request_headers,
&session,
&http_context,
);
Successful::new(session)
},
)
.into_inner();
let data_frame = tracer
.in_span_async(
"create_logical_plan",
"Creates a Logical Plan for the given SQL statement",
SpanVisibility::User,
|| {
Box::pin(async {
let logical_plan = session_context.sql(&request.sql).await?;
set_attribute_on_active_span(
tracing_util::AttributeVisibility::Default,
"logical_plan",
logical_plan.logical_plan().to_string(),
);
Ok::<_, SqlExecutionError>(logical_plan)
})
},
)
.await?;
let physical_plan_options = PhysicalPlanOptions::new(request.disallow_mutations);
let batches = tracer
.in_span_async(
"execute_logical_plan",
"Executes the Logical Plan of a query",
SpanVisibility::User,
|| Box::pin(async { execute_logical_plan(physical_plan_options, data_frame).await }),
)
.await?;
tracer.in_span(
"serialize_record_batch",
"Serializes datafusion's RecordBatch into a JSON array",
SpanVisibility::User,
|| record_batches_to_json_array(&batches),
)
}
async fn execute_logical_plan(
physical_plan_options: PhysicalPlanOptions,
frame: DataFrame,
) -> Result<Vec<RecordBatch>, SqlExecutionError> {
let tracer = tracing_util::global_tracer();
let task_ctx = frame.task_ctx();
let session_config = task_ctx.session_config().clone();
let plan = tracer
.in_span_async(
"create_physical_plan",
"Creates a physical plan from a logical plan",
SpanVisibility::User,
|| {
Box::pin(async {
frame
.create_physical_plan()
.await
.map_err(SqlExecutionError::DataFusion)
})
},
)
.await?;
let record_batches = tracer
.in_span_async(
"execute_physical_plan",
"Executes a physical plan to collect record batches",
SpanVisibility::User,
|| {
let task_ctx = Arc::new(
task_ctx.with_session_config(
session_config
.with_extension(Arc::new(tracing_util::Context::current()))
.with_extension(Arc::new(physical_plan_options)),
),
);
Box::pin(async {
let results =
datafusion::physical_plan::collect(plan.clone(), task_ctx).await?;
set_attribute_on_active_span(
tracing_util::AttributeVisibility::Default,
"total_rows",
results
.iter()
.map(|x| i64::try_from(x.num_rows()).unwrap_or(0))
.sum::<i64>(),
);
// NOTE: we must compute these metrics _after_ running
// datafusion::physical_plan::collect, because otherwise the execution
// metrics will not be populated. Even though 'plan' is not marked
// mutable, it uses interior mutability throughout the structure in order
// to maintain its metrics.
// Compute rows_processed by summing over all subplans -
// we want to know if any of our nodes fetched an unusually high number
// of rows.
let mut rows_fetched: i64 = 0;
plan.apply(|node| {
if node.as_any().is::<NDCQueryPushDown>()
|| node.as_any().is::<NDCAggregatePushdown>()
|| node.as_any().is::<NDCFunctionPushDown>()
|| node.as_any().is::<NDCProcedurePushDown>()
{
if let Some(metrics) = node.metrics() {
if let Some(output_rows) = metrics.output_rows() {
rows_fetched += i64::try_from(output_rows).unwrap_or(0);
}
}
}
Ok(datafusion::common::tree_node::TreeNodeRecursion::Continue)
})?;
set_attribute_on_active_span(
tracing_util::AttributeVisibility::Default,
"rows_fetched",
rows_fetched,
);
// Take elapsed_compute metric from the top level node
if let Some(metrics) = plan.metrics() {
if let Some(value) = metrics.elapsed_compute() {
set_attribute_on_active_span(
tracing_util::AttributeVisibility::Default,
"elapsed_compute",
i64::try_from(value).unwrap_or(0),
);
}
}
Ok::<_, SqlExecutionError>(results)
})
},
)
.await?;
Ok(record_batches)
}
fn record_batches_to_json_array(batches: &[RecordBatch]) -> Result<Vec<u8>, SqlExecutionError> {
if batches
.iter()
.map(datafusion::arrow::array::RecordBatch::num_rows)
.sum::<usize>()
== 0
{
return Ok(vec![b'[', b']']);
}
// Write the record batch out as a JSON array
let buf = Vec::new();
let builder = WriterBuilder::new().with_explicit_nulls(true);
let mut writer = builder.build::<_, JsonArray>(buf);
for batch in batches {
writer.write(batch)?;
}
writer.finish()?;
// Get the underlying buffer back,
Ok(writer.into_inner())
}