Skip to main content

datafusion_datasource/
sink.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Execution plan for writing data to [`DataSink`]s
6
7use 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/// `DataSink` implements writing streams of [`RecordBatch`]es to
32/// user defined destinations.
33///
34/// The `Display` impl is used to format the sink for explain plan
35/// output.
36#[async_trait]
37pub trait DataSink: Any + DisplayAs + Debug + Send + Sync {
38    /// Return a snapshot of the [MetricsSet] for this
39    /// [DataSink].
40    ///
41    /// See [ExecutionPlan::metrics()] for more details
42    fn metrics(&self) -> Option<MetricsSet> {
43        None
44    }
45
46    /// Returns the sink schema
47    fn schema(&self) -> &SchemaRef;
48
49    // TODO add desired input ordering
50    // How does this sink want its input ordered?
51
52    /// Writes the data to the sink, returns the number of values written
53    ///
54    /// This method will be called exactly once during each DML
55    /// statement. Thus prior to return, the sink should do any commit
56    /// or rollback required.
57    async fn write_all(
58        &self,
59        data: SendableRecordBatchStream,
60        context: &Arc<TaskContext>,
61    ) -> Result<u64>;
62
63    /// Serialize this sink into a full protobuf plan node, if it knows how.
64    ///
65    /// Implementations can use `ctx` to encode the input plan, sink-specific
66    /// expressions, and [`DataSinkExec::encode_sort_order`].
67    ///
68    /// Returning `Ok(None)` lets the caller try its extension codec instead.
69    #[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    /// Returns true if the inner type is `T`.
81    pub fn is<T: DataSink>(&self) -> bool {
82        (self as &dyn Any).is::<T>()
83    }
84
85    /// Returns a reference to the inner value as the type `T` if it is of that type.
86    pub fn downcast_ref<T: DataSink>(&self) -> Option<&T> {
87        (self as &dyn Any).downcast_ref()
88    }
89}
90
91/// Execution plan for writing record batches to a [`DataSink`]
92///
93/// Returns a single row with the number of values written
94#[derive(Clone)]
95pub struct DataSinkExec {
96    /// Input plan that produces the record batches to be written.
97    input: Arc<dyn ExecutionPlan>,
98    /// Sink to which to write
99    sink: Arc<dyn DataSink>,
100    /// Schema describing the structure of the output data.
101    count_schema: SchemaRef,
102    /// Optional required sort order for output data.
103    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    /// Create a plan to write to `sink`
115    /// Note: DataSinkExec requires its input to have a single partition.
116    /// If the input has multiple partitions, the physical optimizer will
117    /// automatically insert a Merge-related operator to merge them.
118    /// If you construct PhysicalPlan without going through the physical optimizer,
119    /// you must ensure that the input has a single partition.
120    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    /// Input execution plan
137    pub fn input(&self) -> &Arc<dyn ExecutionPlan> {
138        &self.input
139    }
140
141    /// Returns insert sink
142    pub fn sink(&self) -> &dyn DataSink {
143        self.sink.as_ref()
144    }
145
146    /// Optional sort order for output data
147    pub fn sort_order(&self) -> &Option<LexRequirement> {
148        &self.sort_order
149    }
150
151    /// Encode the optional sink ordering for a protobuf plan node.
152    #[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    /// Decode the optional sink ordering from a protobuf plan node.
185    #[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    /// Return a reference to Any that can be used for downcasting
254    fn properties(&self) -> &Arc<PlanProperties> {
255        &self.cache
256    }
257
258    fn benefits_from_input_partitioning(&self) -> Vec<bool> {
259        // DataSink is responsible for dynamically partitioning its
260        // own input at execution time.
261        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        // DataSink is responsible for dynamically partitioning its
270        // own input at execution time, and so requires a single input partition.
271        InputDistributionRequirements::new(vec![
272            Distribution::SinglePartition;
273            self.children().len()
274        ])
275    }
276
277    fn required_input_ordering(&self) -> Vec<Option<OrderingRequirements>> {
278        // The required input ordering is set externally (e.g. by a `ListingTable`).
279        // Otherwise, there is no specific requirement (i.e. `sort_order` is `None`).
280        vec![self.sort_order.clone().map(Into::into)]
281    }
282
283    fn maintains_input_order(&self) -> Vec<bool> {
284        // Maintains ordering in the sense that the written file will reflect
285        // the ordering of the input. For more context, see:
286        //
287        // https://github.com/apache/datafusion/pull/6354#discussion_r1195284178
288        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    /// Execute the plan and return a stream of `RecordBatch`es for
325    /// the specified partition.
326    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    /// Returns the metrics of the underlying [DataSink]
358    fn metrics(&self) -> Option<MetricsSet> {
359        self.sink.metrics()
360    }
361
362    /// Delegates protobuf serialization to the underlying sink.
363    #[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
372/// Create a output record batch with a count
373///
374/// ```text
375/// +-------+
376/// | count |
377/// +-------+
378/// | 6     |
379/// +-------+
380/// ```
381fn 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    // Define a schema.
389    Arc::new(Schema::new(vec![Field::new(
390        "count",
391        DataType::UInt64,
392        false,
393    )]))
394}