1use std::any::Any;
8use std::fmt;
9use std::fmt::Debug;
10use std::sync::Arc;
11
12use arrow::array::{ArrayRef, RecordBatch, UInt64Array};
13use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
14use datafusion_common::tree_node::TreeNodeRecursion;
15use datafusion_common::{Result, assert_eq_or_internal_err};
16use datafusion_execution::TaskContext;
17use datafusion_physical_expr::{Distribution, EquivalenceProperties, PhysicalExpr};
18use datafusion_physical_expr_common::sort_expr::{LexRequirement, OrderingRequirements};
19use datafusion_physical_plan::metrics::MetricsSet;
20use datafusion_physical_plan::stream::RecordBatchStreamAdapter;
21use datafusion_physical_plan::{
22 ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan,
23 ExecutionPlanProperties, InputDistributionRequirements, Partitioning, PlanProperties,
24 ReplaceChildrenOptions, SendableRecordBatchStream, execute_input_stream,
25};
26
27use async_trait::async_trait;
28use datafusion_physical_plan::execution_plan::{EvaluationType, SchedulingType};
29use futures::StreamExt;
30
31#[async_trait]
37pub trait DataSink: Any + DisplayAs + Debug + Send + Sync {
38 fn metrics(&self) -> Option<MetricsSet> {
43 None
44 }
45
46 fn schema(&self) -> &SchemaRef;
48
49 async fn write_all(
58 &self,
59 data: SendableRecordBatchStream,
60 context: &Arc<TaskContext>,
61 ) -> Result<u64>;
62
63 #[cfg(feature = "proto")]
70 fn try_to_proto(
71 &self,
72 _exec: &DataSinkExec,
73 _ctx: &datafusion_physical_plan::proto::ExecutionPlanEncodeCtx<'_>,
74 ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalPlanNode>> {
75 Ok(None)
76 }
77}
78
79impl dyn DataSink {
80 pub fn is<T: DataSink>(&self) -> bool {
82 (self as &dyn Any).is::<T>()
83 }
84
85 pub fn downcast_ref<T: DataSink>(&self) -> Option<&T> {
87 (self as &dyn Any).downcast_ref()
88 }
89}
90
91#[derive(Clone)]
95pub struct DataSinkExec {
96 input: Arc<dyn ExecutionPlan>,
98 sink: Arc<dyn DataSink>,
100 count_schema: SchemaRef,
102 sort_order: Option<LexRequirement>,
104 cache: Arc<PlanProperties>,
105}
106
107impl Debug for DataSinkExec {
108 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
109 write!(f, "DataSinkExec schema: {}", self.count_schema)
110 }
111}
112
113impl DataSinkExec {
114 pub fn new(
121 input: Arc<dyn ExecutionPlan>,
122 sink: Arc<dyn DataSink>,
123 sort_order: Option<LexRequirement>,
124 ) -> Self {
125 let count_schema = make_count_schema();
126 let cache = Self::create_schema(&input, count_schema);
127 Self {
128 input,
129 sink,
130 count_schema: make_count_schema(),
131 sort_order,
132 cache: Arc::new(cache),
133 }
134 }
135
136 pub fn input(&self) -> &Arc<dyn ExecutionPlan> {
138 &self.input
139 }
140
141 pub fn sink(&self) -> &dyn DataSink {
143 self.sink.as_ref()
144 }
145
146 pub fn sort_order(&self) -> &Option<LexRequirement> {
148 &self.sort_order
149 }
150
151 #[cfg(feature = "proto")]
153 pub fn encode_sort_order(
154 &self,
155 ctx: &datafusion_physical_plan::proto::ExecutionPlanEncodeCtx<'_>,
156 ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalSortExprNodeCollection>>
157 {
158 use datafusion_physical_expr::PhysicalSortExpr;
159 use datafusion_proto_models::protobuf;
160
161 self.sort_order
162 .as_ref()
163 .map(|requirements| {
164 requirements
165 .iter()
166 .map(|requirement| {
167 let expr: PhysicalSortExpr = requirement.to_owned().into();
168 Ok(protobuf::PhysicalSortExprNode {
169 expr: Some(Box::new(ctx.encode_expr(&expr.expr)?)),
170 asc: !expr.options.descending,
171 nulls_first: expr.options.nulls_first,
172 })
173 })
174 .collect::<Result<Vec<_>>>()
175 .map(|physical_sort_expr_nodes| {
176 protobuf::PhysicalSortExprNodeCollection {
177 physical_sort_expr_nodes,
178 }
179 })
180 })
181 .transpose()
182 }
183
184 #[cfg(feature = "proto")]
186 pub fn decode_sort_order(
187 collection: Option<
188 &datafusion_proto_models::protobuf::PhysicalSortExprNodeCollection,
189 >,
190 ctx: &datafusion_physical_plan::proto::ExecutionPlanDecodeCtx<'_>,
191 schema: &Schema,
192 ) -> Result<Option<LexRequirement>> {
193 use arrow::compute::SortOptions;
194 use datafusion_physical_expr::PhysicalSortExpr;
195
196 let Some(collection) = collection else {
197 return Ok(None);
198 };
199 let sort_exprs = collection
200 .physical_sort_expr_nodes
201 .iter()
202 .map(|node| {
203 let expr = node.expr.as_ref().ok_or_else(|| {
204 datafusion_common::internal_datafusion_err!(
205 "Unexpected empty physical expression"
206 )
207 })?;
208 Ok(PhysicalSortExpr {
209 expr: ctx.decode_expr(expr, schema)?,
210 options: SortOptions {
211 descending: !node.asc,
212 nulls_first: node.nulls_first,
213 },
214 })
215 })
216 .collect::<Result<Vec<_>>>()?;
217 Ok(LexRequirement::new(sort_exprs.into_iter().map(Into::into)))
218 }
219
220 fn create_schema(
221 input: &Arc<dyn ExecutionPlan>,
222 schema: SchemaRef,
223 ) -> PlanProperties {
224 let eq_properties = EquivalenceProperties::new(schema);
225 PlanProperties::new(
226 eq_properties,
227 Partitioning::UnknownPartitioning(1),
228 input.pipeline_behavior(),
229 input.boundedness(),
230 )
231 .with_scheduling_type(SchedulingType::Cooperative)
232 .with_evaluation_type(EvaluationType::Eager)
233 }
234}
235
236impl DisplayAs for DataSinkExec {
237 fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
238 match t {
239 DisplayFormatType::Default | DisplayFormatType::Verbose => {
240 write!(f, "DataSinkExec: sink=")?;
241 self.sink.fmt_as(t, f)
242 }
243 DisplayFormatType::TreeRender => self.sink().fmt_as(t, f),
244 }
245 }
246}
247
248impl ExecutionPlan for DataSinkExec {
249 fn name(&self) -> &'static str {
250 "DataSinkExec"
251 }
252
253 fn properties(&self) -> &Arc<PlanProperties> {
255 &self.cache
256 }
257
258 fn benefits_from_input_partitioning(&self) -> Vec<bool> {
259 vec![false]
262 }
263
264 fn required_input_distribution(&self) -> Vec<Distribution> {
265 self.input_distribution_requirements().into_per_child()
266 }
267
268 fn input_distribution_requirements(&self) -> InputDistributionRequirements {
269 InputDistributionRequirements::new(vec![
272 Distribution::SinglePartition;
273 self.children().len()
274 ])
275 }
276
277 fn required_input_ordering(&self) -> Vec<Option<OrderingRequirements>> {
278 vec![self.sort_order.clone().map(Into::into)]
281 }
282
283 fn maintains_input_order(&self) -> Vec<bool> {
284 vec![true]
289 }
290
291 fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
292 vec![&self.input]
293 }
294
295 fn replace_children(
296 self: Arc<Self>,
297 children: Vec<Arc<dyn ExecutionPlan>>,
298 _: ReplaceChildrenOptions,
299 ) -> Result<Arc<dyn ExecutionPlan>> {
300 Ok(Arc::new(Self::new(
301 Arc::clone(&children[0]),
302 Arc::clone(&self.sink),
303 self.sort_order.clone(),
304 )))
305 }
306
307 fn with_new_children(
308 self: Arc<Self>,
309 children: Vec<Arc<dyn ExecutionPlan>>,
310 ) -> Result<Arc<dyn ExecutionPlan>> {
311 self.replace_children(
312 children,
313 ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
314 )
315 }
316
317 fn apply_expressions(
318 &self,
319 _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
320 ) -> Result<TreeNodeRecursion> {
321 Ok(TreeNodeRecursion::Continue)
322 }
323
324 fn execute(
327 &self,
328 partition: usize,
329 context: Arc<TaskContext>,
330 ) -> Result<SendableRecordBatchStream> {
331 assert_eq_or_internal_err!(
332 partition,
333 0,
334 "DataSinkExec can only be called on partition 0!"
335 );
336 let data = execute_input_stream(
337 Arc::clone(&self.input),
338 Arc::clone(self.sink.schema()),
339 0,
340 Arc::clone(&context),
341 )?;
342
343 let count_schema = Arc::clone(&self.count_schema);
344 let sink = Arc::clone(&self.sink);
345
346 let stream = futures::stream::once(async move {
347 sink.write_all(data, &context).await.map(make_count_batch)
348 })
349 .boxed();
350
351 Ok(Box::pin(RecordBatchStreamAdapter::new(
352 count_schema,
353 stream,
354 )))
355 }
356
357 fn metrics(&self) -> Option<MetricsSet> {
359 self.sink.metrics()
360 }
361
362 #[cfg(feature = "proto")]
364 fn try_to_proto(
365 &self,
366 ctx: &datafusion_physical_plan::proto::ExecutionPlanEncodeCtx<'_>,
367 ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalPlanNode>> {
368 self.sink().try_to_proto(self, ctx)
369 }
370}
371
372fn make_count_batch(count: u64) -> RecordBatch {
382 let array = Arc::new(UInt64Array::from(vec![count])) as ArrayRef;
383
384 RecordBatch::try_from_iter_with_nullable(vec![("count", array, false)]).unwrap()
385}
386
387fn make_count_schema() -> SchemaRef {
388 Arc::new(Schema::new(vec![Field::new(
390 "count",
391 DataType::UInt64,
392 false,
393 )]))
394}