Skip to main content

datafusion_catalog/memory/
table.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//! [`MemTable`] for querying `Vec<RecordBatch>` by DataFusion.
6
7use std::collections::HashMap;
8use std::fmt::Debug;
9use std::future::ready;
10use std::sync::Arc;
11
12use crate::TableProvider;
13
14use arrow::array::{Array, ArrayRef, BooleanArray, UInt64Array};
15use arrow::compute::kernels::zip::zip;
16use arrow::compute::{and, filter_record_batch};
17use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
18use arrow::record_batch::RecordBatch;
19use datafusion_common::error::Result;
20use datafusion_common::tree_node::TreeNodeRecursion;
21use datafusion_common::{
22    Constraints, DFSchema, SchemaExt, internal_datafusion_err, internal_err,
23    not_impl_err, plan_err,
24};
25use datafusion_datasource::memory::{MemSink, MemorySourceConfig};
26use datafusion_datasource::sink::DataSinkExec;
27use datafusion_datasource::source::DataSourceExec;
28use datafusion_execution::{SendableRecordBatchStream, TaskContext};
29use datafusion_expr::dml::InsertOp;
30use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
31use datafusion_expr::{Expr, SortExpr, TableType};
32use datafusion_physical_expr::{
33    EquivalenceProperties, LexOrdering, create_physical_expr, create_physical_sort_exprs,
34};
35use datafusion_physical_plan::execution_plan::{Boundedness, EmissionType};
36use datafusion_physical_plan::repartition::RepartitionExec;
37use datafusion_physical_plan::stream::RecordBatchStreamAdapter;
38use datafusion_physical_plan::{
39    ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning,
40    PhysicalExpr, PlanProperties, ReplaceChildrenOptions, apply_expression_roots,
41    collect_partitioned,
42};
43use datafusion_session::Session;
44
45use async_trait::async_trait;
46use futures::future::BoxFuture;
47use log::debug;
48use parking_lot::Mutex;
49use tokio::sync::RwLock;
50
51// backward compatibility
52pub use datafusion_datasource::memory::PartitionData;
53
54/// In-memory data source for presenting a `Vec<RecordBatch>` as a
55/// data source that can be queried by DataFusion. This allows data to
56/// be pre-loaded into memory and then repeatedly queried without
57/// incurring additional file I/O overhead.
58#[derive(Debug)]
59pub struct MemTable {
60    schema: SchemaRef,
61    /// # Public Only for Internal Use:
62    ///
63    /// This is not a public API and is for internal use only; see [API policy] for details.
64    ///
65    /// [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis
66    #[doc(hidden)]
67    pub batches: Vec<PartitionData>,
68    constraints: Constraints,
69    column_defaults: HashMap<String, Expr>,
70    /// Optional pre-known sort order(s). Must be `SortExpr`s.
71    /// inserting data into this table removes the order
72    pub sort_order: Arc<Mutex<Vec<Vec<SortExpr>>>>,
73}
74
75impl MemTable {
76    /// Create a new in-memory table from the provided schema and record batches.
77    ///
78    /// Requires at least one partition. To construct an empty `MemTable`, pass
79    /// `vec![vec![]]` as the `partitions` argument, this represents one partition with
80    /// no batches.
81    pub fn try_new(schema: SchemaRef, partitions: Vec<Vec<RecordBatch>>) -> Result<Self> {
82        if partitions.is_empty() {
83            return plan_err!("No partitions provided, expected at least one partition");
84        }
85
86        for batches in partitions.iter().flatten() {
87            let batches_schema = batches.schema();
88            if !schema.contains(&batches_schema) {
89                debug!(
90                    "mem table schema does not contain batches schema. \
91                        Target_schema: {schema:?}. Batches Schema: {batches_schema:?}"
92                );
93                return plan_err!("Mismatch between schema and batches");
94            }
95        }
96
97        Ok(Self {
98            schema,
99            batches: partitions
100                .into_iter()
101                .map(|e| Arc::new(RwLock::new(e)))
102                .collect::<Vec<_>>(),
103            constraints: Constraints::default(),
104            column_defaults: HashMap::new(),
105            sort_order: Arc::new(Mutex::new(vec![])),
106        })
107    }
108
109    /// Assign constraints
110    pub fn with_constraints(mut self, constraints: Constraints) -> Self {
111        self.constraints = constraints;
112        self
113    }
114
115    /// Assign column defaults
116    pub fn with_column_defaults(
117        mut self,
118        column_defaults: HashMap<String, Expr>,
119    ) -> Self {
120        self.column_defaults = column_defaults;
121        self
122    }
123
124    /// Specify an optional pre-known sort order(s). Must be `SortExpr`s.
125    ///
126    /// If the data is not sorted by this order, DataFusion may produce
127    /// incorrect results.
128    ///
129    /// DataFusion may take advantage of this ordering to omit sorts
130    /// or use more efficient algorithms.
131    ///
132    /// Note that multiple sort orders are supported, if some are known to be
133    /// equivalent,
134    pub fn with_sort_order(self, mut sort_order: Vec<Vec<SortExpr>>) -> Self {
135        std::mem::swap(self.sort_order.lock().as_mut(), &mut sort_order);
136        self
137    }
138
139    /// Create a mem table by reading from another data source
140    pub async fn load(
141        t: Arc<dyn TableProvider>,
142        output_partitions: Option<usize>,
143        state: &dyn Session,
144    ) -> Result<Self> {
145        let schema = t.schema();
146        let constraints = t.constraints().cloned().unwrap_or_default();
147
148        let exec = t.scan(state, None, &[], None).await?;
149        let data = collect_partitioned(exec, state.task_ctx()).await?;
150
151        // Optionally repartition the collected batches.
152        let data = if let Some(num_partitions) = output_partitions {
153            let source = DataSourceExec::new(Arc::new(MemorySourceConfig::try_new(
154                &data,
155                Arc::clone(&schema),
156                None,
157            )?));
158            let exec = RepartitionExec::try_new(
159                Arc::new(source),
160                Partitioning::RoundRobinBatch(num_partitions),
161            )?;
162            collect_partitioned(Arc::new(exec), state.task_ctx()).await?
163        } else {
164            data
165        };
166
167        MemTable::try_new(schema, data).map(|table| table.with_constraints(constraints))
168    }
169}
170
171#[async_trait]
172impl TableProvider for MemTable {
173    fn schema(&self) -> SchemaRef {
174        Arc::clone(&self.schema)
175    }
176
177    fn constraints(&self) -> Option<&Constraints> {
178        Some(&self.constraints)
179    }
180
181    fn table_type(&self) -> TableType {
182        TableType::Base
183    }
184
185    // Hand-written `#[async_trait]` expansion to reduce compile time. See
186    // <https://github.com/apache/datafusion/issues/13814#issuecomment-5292709677>
187    fn scan<'life0, 'life1, 'life2, 'life3, 'async_trait>(
188        &'life0 self,
189        state: &'life1 dyn Session,
190        projection: Option<&'life2 [usize]>,
191        filters: &'life3 [Expr],
192        limit: Option<usize>,
193    ) -> BoxFuture<'async_trait, Result<Arc<dyn ExecutionPlan>>>
194    where
195        'life0: 'async_trait,
196        'life1: 'async_trait,
197        'life2: 'async_trait,
198        'life3: 'async_trait,
199        Self: 'async_trait,
200    {
201        self.scan_boxed(state, projection, filters, limit)
202    }
203
204    /// Returns an ExecutionPlan that inserts the execution results of a given [`ExecutionPlan`] into this [`MemTable`].
205    ///
206    /// The [`ExecutionPlan`] must have the same schema as this [`MemTable`].
207    ///
208    /// # Arguments
209    ///
210    /// * `state` - The [`SessionState`] containing the context for executing the plan.
211    /// * `input` - The [`ExecutionPlan`] to execute and insert.
212    ///
213    /// # Returns
214    ///
215    /// * A plan that returns the number of rows written.
216    ///
217    /// [`SessionState`]: https://docs.rs/datafusion/latest/datafusion/execution/session_state/struct.SessionState.html
218    // Hand-written `#[async_trait]` expansion to reduce compile time. See
219    // <https://github.com/apache/datafusion/issues/13814#issuecomment-5292709677>
220    fn insert_into<'life0, 'life1, 'async_trait>(
221        &'life0 self,
222        state: &'life1 dyn Session,
223        input: Arc<dyn ExecutionPlan>,
224        insert_op: InsertOp,
225    ) -> BoxFuture<'async_trait, Result<Arc<dyn ExecutionPlan>>>
226    where
227        'life0: 'async_trait,
228        'life1: 'async_trait,
229        Self: 'async_trait,
230    {
231        self.insert_into_boxed(state, input, insert_op)
232    }
233
234    fn get_column_default(&self, column: &str) -> Option<&Expr> {
235        self.column_defaults.get(column)
236    }
237
238    // Hand-written `#[async_trait]` expansion to reduce compile time. See
239    // <https://github.com/apache/datafusion/issues/13814#issuecomment-5292709677>
240    fn delete_from<'life0, 'life1, 'async_trait>(
241        &'life0 self,
242        state: &'life1 dyn Session,
243        filters: Vec<Expr>,
244    ) -> BoxFuture<'async_trait, Result<Arc<dyn ExecutionPlan>>>
245    where
246        'life0: 'async_trait,
247        'life1: 'async_trait,
248        Self: 'async_trait,
249    {
250        // Planning a `DELETE` needs no await, so the future is ready at once.
251        Box::pin(ready(self.delete_from_inner(state, &filters)))
252    }
253
254    // Hand-written `#[async_trait]` expansion to reduce compile time. See
255    // <https://github.com/apache/datafusion/issues/13814#issuecomment-5292709677>
256    fn update<'life0, 'life1, 'async_trait>(
257        &'life0 self,
258        state: &'life1 dyn Session,
259        assignments: Vec<(String, Expr)>,
260        filters: Vec<Expr>,
261    ) -> BoxFuture<'async_trait, Result<Arc<dyn ExecutionPlan>>>
262    where
263        'life0: 'async_trait,
264        'life1: 'async_trait,
265        Self: 'async_trait,
266    {
267        // Planning an `UPDATE` needs no await, so the future is ready at once.
268        Box::pin(ready(self.update_inner(state, &assignments, &filters)))
269    }
270}
271
272impl MemTable {
273    fn scan_boxed<'a>(
274        &'a self,
275        state: &'a dyn Session,
276        projection: Option<&'a [usize]>,
277        filters: &'a [Expr],
278        limit: Option<usize>,
279    ) -> BoxFuture<'a, Result<Arc<dyn ExecutionPlan>>> {
280        Box::pin(self.scan_inner(state, projection, filters, limit))
281    }
282
283    async fn scan_inner(
284        &self,
285        state: &dyn Session,
286        projection: Option<&[usize]>,
287        _filters: &[Expr],
288        _limit: Option<usize>,
289    ) -> Result<Arc<dyn ExecutionPlan>> {
290        let mut partitions = Vec::with_capacity(self.batches.len());
291        for arc_inner_vec in self.batches.iter() {
292            let inner_vec = arc_inner_vec.read().await;
293            partitions.push(inner_vec.clone())
294        }
295
296        let mut source = MemorySourceConfig::try_new(
297            &partitions,
298            self.schema(),
299            projection.map(|p| p.to_vec()),
300        )?;
301
302        let show_sizes = state.config_options().explain.show_sizes;
303        source = source.with_show_sizes(show_sizes);
304
305        // add sort information if present
306        let sort_order = self.sort_order.lock();
307        if !sort_order.is_empty() {
308            let df_schema = DFSchema::try_from(Arc::clone(&self.schema))?;
309
310            let eqp = state.execution_props();
311            let mut file_sort_order = Vec::with_capacity(sort_order.len());
312            for sort_exprs in sort_order.iter() {
313                let physical_exprs = create_physical_sort_exprs(
314                    sort_exprs,
315                    &df_schema,
316                    eqp,
317                    &PhysicalPlanningContext::default(),
318                )?;
319                file_sort_order.extend(LexOrdering::new(physical_exprs));
320            }
321            source = source.try_with_sort_information(file_sort_order)?;
322        }
323
324        Ok(DataSourceExec::from_data_source(source))
325    }
326
327    fn insert_into_boxed<'a>(
328        &'a self,
329        state: &'a dyn Session,
330        input: Arc<dyn ExecutionPlan>,
331        insert_op: InsertOp,
332    ) -> BoxFuture<'a, Result<Arc<dyn ExecutionPlan>>> {
333        Box::pin(ready(self.insert_into_inner(state, input, insert_op)))
334    }
335
336    fn insert_into_inner(
337        &self,
338        _state: &dyn Session,
339        input: Arc<dyn ExecutionPlan>,
340        insert_op: InsertOp,
341    ) -> Result<Arc<dyn ExecutionPlan>> {
342        // If we are inserting into the table, any sort order may be messed up so reset it here
343        *self.sort_order.lock() = vec![];
344
345        // Create a physical plan from the logical plan.
346        // Check that the schema of the plan matches the schema of this table.
347        self.schema()
348            .logically_equivalent_names_and_types(&input.schema())?;
349
350        if insert_op == InsertOp::Replace {
351            return not_impl_err!("{insert_op} not implemented for MemoryTable yet");
352        }
353        let sink = MemSink::try_new(self.batches.clone(), Arc::clone(&self.schema))?
354            .with_overwrite(insert_op == InsertOp::Overwrite);
355        Ok(Arc::new(DataSinkExec::new(input, Arc::new(sink), None)))
356    }
357
358    /// Plan a `DELETE`. The rows change when the returned plan runs, not here,
359    /// so `EXPLAIN DELETE` prints the plan and the table keeps its rows.
360    fn delete_from_inner(
361        &self,
362        state: &dyn Session,
363        filters: &[Expr],
364    ) -> Result<Arc<dyn ExecutionPlan>> {
365        let df_schema = DFSchema::try_from(Arc::clone(&self.schema))?;
366        let predicates = create_predicates(filters, &df_schema, state)?;
367
368        Ok(Arc::new(MemDeleteExec::new(
369            self.batches.clone(),
370            Arc::clone(&self.sort_order),
371            predicates,
372        )))
373    }
374
375    /// Plan an `UPDATE`. The rows change when the returned plan runs, not here,
376    /// so `EXPLAIN UPDATE` prints the plan and the table keeps its rows.
377    fn update_inner(
378        &self,
379        state: &dyn Session,
380        assignments: &[(String, Expr)],
381        filters: &[Expr],
382    ) -> Result<Arc<dyn ExecutionPlan>> {
383        let df_schema = DFSchema::try_from(Arc::clone(&self.schema))?;
384
385        // One entry for each field of the table, in field order. A `Some` entry
386        // holds the expression of the `SET` clause for that field.
387        let mut set_exprs: Vec<Option<Arc<dyn PhysicalExpr>>> =
388            vec![None; self.schema.fields().len()];
389        for (column_name, expr) in assignments {
390            let Ok(index) = self.schema.index_of(column_name) else {
391                let available_columns: Vec<&str> = self
392                    .schema
393                    .fields()
394                    .iter()
395                    .map(|f| f.name().as_str())
396                    .collect();
397                return plan_err!(
398                    "UPDATE failed: column '{}' does not exist. Available columns: {}",
399                    column_name,
400                    available_columns.join(", ")
401                );
402            };
403            set_exprs[index] = Some(create_physical_expr(
404                expr,
405                &df_schema,
406                state.execution_props(),
407                &PhysicalPlanningContext::default(),
408            )?);
409        }
410
411        let predicates = create_predicates(filters, &df_schema, state)?;
412
413        Ok(Arc::new(MemUpdateExec::new(
414            self.batches.clone(),
415            Arc::clone(&self.sort_order),
416            Arc::clone(&self.schema),
417            set_exprs,
418            predicates,
419        )))
420    }
421}
422
423/// Build one physical predicate for each expression of the `WHERE` clause.
424///
425/// The planner calls this, so a predicate that cannot be planned raises its
426/// error while the plan is built and `EXPLAIN` reports it.
427fn create_predicates(
428    filters: &[Expr],
429    df_schema: &DFSchema,
430    state: &dyn Session,
431) -> Result<Vec<Arc<dyn PhysicalExpr>>> {
432    filters
433        .iter()
434        .map(|filter| {
435            create_physical_expr(
436                filter,
437                df_schema,
438                state.execution_props(),
439                &PhysicalPlanningContext::default(),
440            )
441        })
442        .collect()
443}
444
445/// Combine the predicates into one mask over the rows of `batch`. The mask is
446/// true for a row that every predicate matches. `None` means there is no
447/// `WHERE` clause, which matches every row.
448fn evaluate_predicates(
449    predicates: &[Arc<dyn PhysicalExpr>],
450    batch: &RecordBatch,
451) -> Result<Option<BooleanArray>> {
452    let mut combined_mask: Option<BooleanArray> = None;
453
454    for predicate in predicates {
455        let result = predicate.evaluate(batch)?;
456        let array = result.into_array(batch.num_rows())?;
457        let bool_array = array
458            .as_any()
459            .downcast_ref::<BooleanArray>()
460            .ok_or_else(|| {
461                internal_datafusion_err!("Filter did not evaluate to boolean")
462            })?
463            .clone();
464
465        combined_mask = Some(match combined_mask {
466            Some(existing) => and(&existing, &bool_array)?,
467            None => bool_array,
468        });
469    }
470
471    Ok(combined_mask)
472}
473
474/// Schema of the single `count` column that a DML plan emits.
475fn dml_count_schema() -> SchemaRef {
476    Arc::new(Schema::new(vec![Field::new(
477        "count",
478        DataType::UInt64,
479        false,
480    )]))
481}
482
483/// Properties of a DML plan: one partition, one final batch.
484fn dml_plan_properties(schema: &SchemaRef) -> Arc<PlanProperties> {
485    Arc::new(PlanProperties::new(
486        EquivalenceProperties::new(Arc::clone(schema)),
487        Partitioning::UnknownPartitioning(1),
488        EmissionType::Final,
489        Boundedness::Bounded,
490    ))
491}
492
493/// A single row holding the number of rows the statement changed.
494fn count_batch(schema: SchemaRef, rows_affected: u64) -> Result<RecordBatch> {
495    let count_array = UInt64Array::from(vec![rows_affected]);
496    Ok(RecordBatch::try_new(
497        schema,
498        vec![Arc::new(count_array) as ArrayRef],
499    )?)
500}
501
502/// Render the predicates as a comma separated list.
503fn format_predicates(predicates: &[Arc<dyn PhysicalExpr>]) -> String {
504    predicates
505        .iter()
506        .map(|predicate| predicate.to_string())
507        .collect::<Vec<_>>()
508        .join(", ")
509}
510
511/// Deletes the matching rows of a [`MemTable`] when it runs, and emits the count.
512///
513/// The provider hook that builds this node changes no row, so `EXPLAIN DELETE`
514/// prints the plan and the table keeps its rows. Each run of the plan applies
515/// the delete once, as [`DataSinkExec`] does for an `INSERT`.
516#[derive(Debug)]
517struct MemDeleteExec {
518    /// Partitions of the target table, shared with the [`MemTable`].
519    partitions: Vec<PartitionData>,
520    /// Declared sort order of the target table. A delete clears it.
521    sort_order: Arc<Mutex<Vec<Vec<SortExpr>>>>,
522    /// Predicates of the `WHERE` clause. An empty list matches every row.
523    predicates: Vec<Arc<dyn PhysicalExpr>>,
524    /// Single `count` column of the output.
525    schema: SchemaRef,
526    properties: Arc<PlanProperties>,
527}
528
529impl MemDeleteExec {
530    fn new(
531        partitions: Vec<PartitionData>,
532        sort_order: Arc<Mutex<Vec<Vec<SortExpr>>>>,
533        predicates: Vec<Arc<dyn PhysicalExpr>>,
534    ) -> Self {
535        let schema = dml_count_schema();
536        let properties = dml_plan_properties(&schema);
537
538        Self {
539            partitions,
540            sort_order,
541            predicates,
542            schema,
543            properties,
544        }
545    }
546}
547
548impl DisplayAs for MemDeleteExec {
549    fn fmt_as(
550        &self,
551        t: DisplayFormatType,
552        f: &mut std::fmt::Formatter,
553    ) -> std::fmt::Result {
554        match t {
555            DisplayFormatType::Default
556            | DisplayFormatType::Verbose
557            | DisplayFormatType::TreeRender => {
558                write!(f, "MemDeleteExec")?;
559                if !self.predicates.is_empty() {
560                    write!(f, ": predicate=[{}]", format_predicates(&self.predicates))?;
561                }
562                Ok(())
563            }
564        }
565    }
566}
567
568impl ExecutionPlan for MemDeleteExec {
569    fn name(&self) -> &str {
570        "MemDeleteExec"
571    }
572
573    fn schema(&self) -> SchemaRef {
574        Arc::clone(&self.schema)
575    }
576
577    fn properties(&self) -> &Arc<PlanProperties> {
578        &self.properties
579    }
580
581    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
582        vec![]
583    }
584
585    fn replace_children(
586        self: Arc<Self>,
587        _: Vec<Arc<dyn ExecutionPlan>>,
588        _: ReplaceChildrenOptions,
589    ) -> Result<Arc<dyn ExecutionPlan>> {
590        Ok(self)
591    }
592
593    fn with_new_children(
594        self: Arc<Self>,
595        children: Vec<Arc<dyn ExecutionPlan>>,
596    ) -> Result<Arc<dyn ExecutionPlan>> {
597        self.replace_children(
598            children,
599            ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
600        )
601    }
602
603    fn execute(
604        &self,
605        partition: usize,
606        _context: Arc<TaskContext>,
607    ) -> Result<SendableRecordBatchStream> {
608        if partition != 0 {
609            return internal_err!(
610                "MemDeleteExec has one partition, but partition {partition} was requested"
611            );
612        }
613
614        let partitions = self.partitions.clone();
615        let sort_order = Arc::clone(&self.sort_order);
616        let predicates = self.predicates.clone();
617        let schema = self.schema();
618
619        let stream = futures::stream::once(async move {
620            let rows_affected =
621                delete_rows(&partitions, &sort_order, &predicates).await?;
622            count_batch(schema, rows_affected)
623        });
624
625        Ok(Box::pin(RecordBatchStreamAdapter::new(
626            self.schema(),
627            stream,
628        )))
629    }
630
631    fn apply_expressions(
632        &self,
633        f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
634    ) -> Result<TreeNodeRecursion> {
635        apply_expression_roots(&self.predicates, f)
636    }
637}
638
639/// Delete the matching rows of every partition and return how many it removed.
640async fn delete_rows(
641    partitions: &[PartitionData],
642    sort_order: &Mutex<Vec<Vec<SortExpr>>>,
643    predicates: &[Arc<dyn PhysicalExpr>],
644) -> Result<u64> {
645    // The surviving rows hold no known order.
646    *sort_order.lock() = vec![];
647
648    let mut total_deleted: u64 = 0;
649
650    for partition_data in partitions {
651        let mut partition = partition_data.write().await;
652        let mut new_batches = Vec::with_capacity(partition.len());
653
654        for batch in partition.iter() {
655            if batch.num_rows() == 0 {
656                continue;
657            }
658
659            let (delete_count, keep_mask) = match evaluate_predicates(predicates, batch)?
660            {
661                Some(mask) => {
662                    // Count the rows the mask selects, which are the rows to delete.
663                    let count = mask.iter().filter(|v| v == &Some(true)).count();
664                    // Keep the rows for which the predicate is false or NULL,
665                    // which follows SQL three-valued logic.
666                    let keep: BooleanArray =
667                        mask.iter().map(|v| Some(v != Some(true))).collect();
668                    (count, keep)
669                }
670                None => {
671                    // No `WHERE` clause deletes every row.
672                    (
673                        batch.num_rows(),
674                        BooleanArray::from(vec![false; batch.num_rows()]),
675                    )
676                }
677            };
678
679            total_deleted += delete_count as u64;
680
681            let filtered_batch = filter_record_batch(batch, &keep_mask)?;
682            if filtered_batch.num_rows() > 0 {
683                new_batches.push(filtered_batch);
684            }
685        }
686
687        *partition = new_batches;
688    }
689
690    Ok(total_deleted)
691}
692
693/// Updates the matching rows of a [`MemTable`] when it runs, and emits the count.
694///
695/// The provider hook that builds this node changes no row, so `EXPLAIN UPDATE`
696/// prints the plan and the table keeps its rows. Each run of the plan applies
697/// the update once, as [`DataSinkExec`] does for an `INSERT`.
698#[derive(Debug)]
699struct MemUpdateExec {
700    /// Partitions of the target table, shared with the [`MemTable`].
701    partitions: Vec<PartitionData>,
702    /// Declared sort order of the target table. An update clears it.
703    sort_order: Arc<Mutex<Vec<Vec<SortExpr>>>>,
704    /// Schema of the target table.
705    table_schema: SchemaRef,
706    /// One entry for each field of the target table, in field order. A `Some`
707    /// entry holds the expression of the `SET` clause for that field.
708    set_exprs: Vec<Option<Arc<dyn PhysicalExpr>>>,
709    /// Predicates of the `WHERE` clause. An empty list matches every row.
710    predicates: Vec<Arc<dyn PhysicalExpr>>,
711    /// Single `count` column of the output.
712    schema: SchemaRef,
713    properties: Arc<PlanProperties>,
714}
715
716impl MemUpdateExec {
717    fn new(
718        partitions: Vec<PartitionData>,
719        sort_order: Arc<Mutex<Vec<Vec<SortExpr>>>>,
720        table_schema: SchemaRef,
721        set_exprs: Vec<Option<Arc<dyn PhysicalExpr>>>,
722        predicates: Vec<Arc<dyn PhysicalExpr>>,
723    ) -> Self {
724        let schema = dml_count_schema();
725        let properties = dml_plan_properties(&schema);
726
727        Self {
728            partitions,
729            sort_order,
730            table_schema,
731            set_exprs,
732            predicates,
733            schema,
734            properties,
735        }
736    }
737
738    /// Render the `SET` clauses as `column=expression`, in field order.
739    fn format_set_exprs(&self) -> String {
740        self.table_schema
741            .fields()
742            .iter()
743            .zip(&self.set_exprs)
744            .filter_map(|(field, set_expr)| {
745                set_expr
746                    .as_ref()
747                    .map(|expr| format!("{}={}", field.name(), expr))
748            })
749            .collect::<Vec<_>>()
750            .join(", ")
751    }
752}
753
754impl DisplayAs for MemUpdateExec {
755    fn fmt_as(
756        &self,
757        t: DisplayFormatType,
758        f: &mut std::fmt::Formatter,
759    ) -> std::fmt::Result {
760        match t {
761            DisplayFormatType::Default
762            | DisplayFormatType::Verbose
763            | DisplayFormatType::TreeRender => {
764                write!(f, "MemUpdateExec: set=[{}]", self.format_set_exprs())?;
765                if !self.predicates.is_empty() {
766                    write!(f, ", predicate=[{}]", format_predicates(&self.predicates))?;
767                }
768                Ok(())
769            }
770        }
771    }
772}
773
774impl ExecutionPlan for MemUpdateExec {
775    fn name(&self) -> &str {
776        "MemUpdateExec"
777    }
778
779    fn schema(&self) -> SchemaRef {
780        Arc::clone(&self.schema)
781    }
782
783    fn properties(&self) -> &Arc<PlanProperties> {
784        &self.properties
785    }
786
787    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
788        vec![]
789    }
790
791    fn replace_children(
792        self: Arc<Self>,
793        _: Vec<Arc<dyn ExecutionPlan>>,
794        _: ReplaceChildrenOptions,
795    ) -> Result<Arc<dyn ExecutionPlan>> {
796        Ok(self)
797    }
798
799    fn with_new_children(
800        self: Arc<Self>,
801        children: Vec<Arc<dyn ExecutionPlan>>,
802    ) -> Result<Arc<dyn ExecutionPlan>> {
803        self.replace_children(
804            children,
805            ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
806        )
807    }
808
809    fn execute(
810        &self,
811        partition: usize,
812        _context: Arc<TaskContext>,
813    ) -> Result<SendableRecordBatchStream> {
814        if partition != 0 {
815            return internal_err!(
816                "MemUpdateExec has one partition, but partition {partition} was requested"
817            );
818        }
819
820        let partitions = self.partitions.clone();
821        let sort_order = Arc::clone(&self.sort_order);
822        let table_schema = Arc::clone(&self.table_schema);
823        let set_exprs = self.set_exprs.clone();
824        let predicates = self.predicates.clone();
825        let schema = self.schema();
826
827        let stream = futures::stream::once(async move {
828            let rows_affected = update_rows(
829                &partitions,
830                &sort_order,
831                &table_schema,
832                &set_exprs,
833                &predicates,
834            )
835            .await?;
836            count_batch(schema, rows_affected)
837        });
838
839        Ok(Box::pin(RecordBatchStreamAdapter::new(
840            self.schema(),
841            stream,
842        )))
843    }
844
845    fn apply_expressions(
846        &self,
847        f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
848    ) -> Result<TreeNodeRecursion> {
849        match apply_expression_roots(self.set_exprs.iter().flatten(), f)? {
850            TreeNodeRecursion::Stop => Ok(TreeNodeRecursion::Stop),
851            TreeNodeRecursion::Continue | TreeNodeRecursion::Jump => {
852                apply_expression_roots(&self.predicates, f)
853            }
854        }
855    }
856}
857
858/// Apply the `SET` clauses to the matching rows of every partition and return
859/// how many rows changed.
860async fn update_rows(
861    partitions: &[PartitionData],
862    sort_order: &Mutex<Vec<Vec<SortExpr>>>,
863    table_schema: &SchemaRef,
864    set_exprs: &[Option<Arc<dyn PhysicalExpr>>],
865    predicates: &[Arc<dyn PhysicalExpr>],
866) -> Result<u64> {
867    // The new values hold no known order.
868    *sort_order.lock() = vec![];
869
870    let mut total_updated: u64 = 0;
871
872    for partition_data in partitions {
873        let mut partition = partition_data.write().await;
874        let mut new_batches = Vec::with_capacity(partition.len());
875
876        for batch in partition.iter() {
877            if batch.num_rows() == 0 {
878                continue;
879            }
880
881            let (update_count, update_mask) =
882                match evaluate_predicates(predicates, batch)? {
883                    Some(mask) => {
884                        // Count the rows the mask selects, which are the rows to update.
885                        let count = mask.iter().filter(|v| v == &Some(true)).count();
886                        // Only true, never NULL, selects a row for update.
887                        let normalized: BooleanArray =
888                            mask.iter().map(|v| Some(v == Some(true))).collect();
889                        (count, normalized)
890                    }
891                    None => {
892                        // No `WHERE` clause updates every row.
893                        (
894                            batch.num_rows(),
895                            BooleanArray::from(vec![true; batch.num_rows()]),
896                        )
897                    }
898                };
899
900            total_updated += update_count as u64;
901
902            if update_count == 0 {
903                new_batches.push(batch.clone());
904                continue;
905            }
906
907            let mut new_columns: Vec<ArrayRef> = Vec::with_capacity(batch.num_columns());
908
909            for (index, field) in table_schema.fields().iter().enumerate() {
910                let column_name = field.name();
911                let original_column =
912                    batch.column_by_name(column_name).ok_or_else(|| {
913                        internal_datafusion_err!(
914                            "Column '{column_name}' not found in batch"
915                        )
916                    })?;
917
918                let new_column = match set_exprs.get(index).and_then(|e| e.as_ref()) {
919                    Some(set_expr) => {
920                        // `evaluate_selection` evaluates the matching rows only,
921                        // which keeps an error such as a divide by zero away from
922                        // the rows the statement does not touch. It returns NULL
923                        // for the other rows, and `zip` puts the originals back.
924                        let new_values =
925                            set_expr.evaluate_selection(batch, &update_mask)?;
926                        let new_array = new_values.into_array(batch.num_rows())?;
927
928                        // Convert to &dyn Array, which implements Datum
929                        let new_arr: &dyn Array = new_array.as_ref();
930                        let orig_arr: &dyn Array = original_column.as_ref();
931                        zip(&update_mask, &new_arr, &orig_arr)?
932                    }
933                    None => Arc::clone(original_column),
934                };
935
936                new_columns.push(new_column);
937            }
938
939            let updated_batch =
940                RecordBatch::try_new(Arc::clone(table_schema), new_columns)?;
941            new_batches.push(updated_batch);
942        }
943
944        *partition = new_batches;
945    }
946
947    Ok(total_updated)
948}