Skip to main content

datafusion_catalog/
stream.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//! TableProvider for stream sources, such as FIFO files
6
7use std::fmt::Formatter;
8use std::fs::{File, OpenOptions};
9use std::future::ready;
10use std::io::BufReader;
11use std::path::PathBuf;
12use std::str::FromStr;
13use std::sync::Arc;
14
15use crate::{Session, TableProvider, TableProviderFactory};
16use arrow::array::{RecordBatch, RecordBatchReader, RecordBatchWriter};
17use arrow::datatypes::SchemaRef;
18use datafusion_common::{Constraints, DataFusionError, Result, config_err, plan_err};
19use datafusion_common_runtime::SpawnedTask;
20use datafusion_datasource::sink::{DataSink, DataSinkExec};
21use datafusion_execution::{SendableRecordBatchStream, TaskContext};
22use datafusion_expr::dml::InsertOp;
23use datafusion_expr::{CreateExternalTable, Expr, SortExpr, TableType};
24use datafusion_physical_expr::create_lex_ordering;
25use datafusion_physical_plan::stream::RecordBatchReceiverStreamBuilder;
26use datafusion_physical_plan::streaming::{PartitionStream, StreamingTableExec};
27use datafusion_physical_plan::{DisplayAs, DisplayFormatType, ExecutionPlan};
28
29use async_trait::async_trait;
30use futures::StreamExt;
31use futures::future::BoxFuture;
32
33/// A [`TableProviderFactory`] for [`StreamTable`]
34#[derive(Debug, Default)]
35pub struct StreamTableFactory {}
36
37#[async_trait]
38impl TableProviderFactory for StreamTableFactory {
39    // Hand-written `#[async_trait]` expansion to reduce compile time. See
40    // <https://github.com/apache/datafusion/issues/13814#issuecomment-5292709677>
41    fn create<'life0, 'life1, 'life2, 'async_trait>(
42        &'life0 self,
43        state: &'life1 dyn Session,
44        cmd: &'life2 CreateExternalTable,
45    ) -> BoxFuture<'async_trait, Result<Arc<dyn TableProvider>>>
46    where
47        'life0: 'async_trait,
48        'life1: 'async_trait,
49        'life2: 'async_trait,
50        Self: 'async_trait,
51    {
52        self.create_boxed(state, cmd)
53    }
54}
55
56impl StreamTableFactory {
57    fn create_boxed<'a>(
58        &'a self,
59        state: &'a dyn Session,
60        cmd: &'a CreateExternalTable,
61    ) -> BoxFuture<'a, Result<Arc<dyn TableProvider>>> {
62        Box::pin(ready(self.create_inner(state, cmd)))
63    }
64
65    fn create_inner(
66        &self,
67        state: &dyn Session,
68        cmd: &CreateExternalTable,
69    ) -> Result<Arc<dyn TableProvider>> {
70        let schema: SchemaRef = Arc::clone(cmd.schema.inner());
71        let location = match cmd.locations.as_slice() {
72            [single] => single.clone(),
73            _ => {
74                return config_err!(
75                    "Stream tables support exactly one location; \
76                     use a listing table to read multiple files"
77                );
78            }
79        };
80        let encoding = cmd.file_type.parse()?;
81        let header = if let Ok(opt) = cmd
82            .options
83            .get("format.has_header")
84            .map(|has_header| bool::from_str(has_header.to_lowercase().as_str()))
85            .transpose()
86        {
87            opt.unwrap_or(false)
88        } else {
89            return config_err!(
90                "Valid values for format.has_header option are 'true' or 'false'"
91            );
92        };
93
94        let source = FileStreamProvider::new_file(schema, location.into())
95            .with_encoding(encoding)
96            .with_batch_size(state.config().batch_size())
97            .with_header(header);
98
99        let config = StreamConfig::new(Arc::new(source))
100            .with_order(cmd.order_exprs.clone())
101            .with_constraints(cmd.constraints.clone());
102
103        Ok(Arc::new(StreamTable(Arc::new(config))))
104    }
105}
106
107/// The data encoding for [`StreamTable`]
108#[derive(Debug, Clone)]
109pub enum StreamEncoding {
110    /// CSV records
111    Csv,
112    /// Newline-delimited JSON records
113    Json,
114}
115
116impl FromStr for StreamEncoding {
117    type Err = DataFusionError;
118
119    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
120        match s.to_ascii_lowercase().as_str() {
121            "csv" => Ok(Self::Csv),
122            "json" => Ok(Self::Json),
123            _ => plan_err!("Unrecognized StreamEncoding {}", s),
124        }
125    }
126}
127
128/// The StreamProvider trait is used as a generic interface for reading and writing from streaming
129/// data sources (such as FIFO, Websocket, Kafka, etc.).  Implementations of the provider are
130/// responsible for providing a `RecordBatchReader` and optionally a `RecordBatchWriter`.
131pub trait StreamProvider: std::fmt::Debug + Send + Sync {
132    /// Get a reference to the schema for this stream
133    fn schema(&self) -> &SchemaRef;
134    /// Provide `RecordBatchReader`
135    fn reader(&self) -> Result<Box<dyn RecordBatchReader>>;
136    /// Provide `RecordBatchWriter`
137    fn writer(&self) -> Result<Box<dyn RecordBatchWriter>> {
138        unimplemented!()
139    }
140    /// Display implementation when using as a DataSink
141    fn stream_write_display(
142        &self,
143        t: DisplayFormatType,
144        f: &mut Formatter,
145    ) -> std::fmt::Result;
146}
147
148/// Stream data from the file at `location`
149///
150/// * Data will be read sequentially from the provided `location`
151/// * New data will be appended to the end of the file
152///
153/// The encoding can be configured with [`Self::with_encoding`] and
154/// defaults to [`StreamEncoding::Csv`]
155#[derive(Debug)]
156pub struct FileStreamProvider {
157    location: PathBuf,
158    encoding: StreamEncoding,
159    /// Get a reference to the schema for this file stream
160    pub schema: SchemaRef,
161    header: bool,
162    batch_size: usize,
163}
164
165impl FileStreamProvider {
166    /// Stream data from the file at `location`
167    ///
168    /// * Data will be read sequentially from the provided `location`
169    /// * New data will be appended to the end of the file
170    ///
171    /// The encoding can be configured with [`Self::with_encoding`] and
172    /// defaults to [`StreamEncoding::Csv`]
173    pub fn new_file(schema: SchemaRef, location: PathBuf) -> Self {
174        Self {
175            schema,
176            location,
177            batch_size: 1024,
178            encoding: StreamEncoding::Csv,
179            header: false,
180        }
181    }
182
183    /// Set the batch size (the number of rows to load at one time)
184    pub fn with_batch_size(mut self, batch_size: usize) -> Self {
185        self.batch_size = batch_size;
186        self
187    }
188
189    /// Specify whether the file has a header (only applicable for [`StreamEncoding::Csv`])
190    pub fn with_header(mut self, header: bool) -> Self {
191        self.header = header;
192        self
193    }
194
195    /// Specify an encoding for the stream
196    pub fn with_encoding(mut self, encoding: StreamEncoding) -> Self {
197        self.encoding = encoding;
198        self
199    }
200}
201
202impl StreamProvider for FileStreamProvider {
203    fn schema(&self) -> &SchemaRef {
204        &self.schema
205    }
206
207    fn reader(&self) -> Result<Box<dyn RecordBatchReader>> {
208        let file = File::open(&self.location)?;
209        let schema = Arc::clone(&self.schema);
210        match &self.encoding {
211            StreamEncoding::Csv => {
212                let reader = arrow::csv::ReaderBuilder::new(schema)
213                    .with_header(self.header)
214                    .with_batch_size(self.batch_size)
215                    .build(file)?;
216
217                Ok(Box::new(reader))
218            }
219            StreamEncoding::Json => {
220                let reader = arrow::json::ReaderBuilder::new(schema)
221                    .with_batch_size(self.batch_size)
222                    .build(BufReader::new(file))?;
223
224                Ok(Box::new(reader))
225            }
226        }
227    }
228
229    fn writer(&self) -> Result<Box<dyn RecordBatchWriter>> {
230        match &self.encoding {
231            StreamEncoding::Csv => {
232                let header = self.header && !self.location.exists();
233                let file = OpenOptions::new()
234                    .create(true)
235                    .append(true)
236                    .open(&self.location)?;
237                let writer = arrow::csv::WriterBuilder::new()
238                    .with_header(header)
239                    .build(file);
240
241                Ok(Box::new(writer))
242            }
243            StreamEncoding::Json => {
244                let file = OpenOptions::new()
245                    .create(true)
246                    .append(true)
247                    .open(&self.location)?;
248                Ok(Box::new(arrow::json::LineDelimitedWriter::new(file)))
249            }
250        }
251    }
252
253    fn stream_write_display(
254        &self,
255        _t: DisplayFormatType,
256        f: &mut Formatter,
257    ) -> std::fmt::Result {
258        f.debug_struct("StreamWrite")
259            .field("location", &self.location)
260            .field("batch_size", &self.batch_size)
261            .field("encoding", &self.encoding)
262            .field("header", &self.header)
263            .finish_non_exhaustive()
264    }
265}
266
267/// The configuration for a [`StreamTable`]
268#[derive(Debug)]
269pub struct StreamConfig {
270    source: Arc<dyn StreamProvider>,
271    order: Vec<Vec<SortExpr>>,
272    constraints: Constraints,
273}
274
275impl StreamConfig {
276    /// Create a new `StreamConfig` from a `StreamProvider`
277    pub fn new(source: Arc<dyn StreamProvider>) -> Self {
278        Self {
279            source,
280            order: vec![],
281            constraints: Constraints::default(),
282        }
283    }
284
285    /// Specify a sort order for the stream
286    pub fn with_order(mut self, order: Vec<Vec<SortExpr>>) -> Self {
287        self.order = order;
288        self
289    }
290
291    /// Assign constraints
292    pub fn with_constraints(mut self, constraints: Constraints) -> Self {
293        self.constraints = constraints;
294        self
295    }
296
297    fn reader(&self) -> Result<Box<dyn RecordBatchReader>> {
298        self.source.reader()
299    }
300
301    fn writer(&self) -> Result<Box<dyn RecordBatchWriter>> {
302        self.source.writer()
303    }
304}
305
306/// A [`TableProvider`] for an unbounded stream source
307///
308/// Currently only reading from / appending to a single file in-place is supported, but
309/// other stream sources and sinks may be added in future.
310///
311/// Applications looking to read/write datasets comprising multiple files, e.g. [Hadoop]-style
312/// data stored in object storage, should instead consider [`ListingTable`].
313///
314/// [Hadoop]: https://hadoop.apache.org/
315/// [`ListingTable`]: https://docs.rs/datafusion/latest/datafusion/datasource/listing/struct.ListingTable.html
316#[derive(Debug)]
317pub struct StreamTable(Arc<StreamConfig>);
318
319impl StreamTable {
320    /// Create a new [`StreamTable`] for the given [`StreamConfig`]
321    pub fn new(config: Arc<StreamConfig>) -> Self {
322        Self(config)
323    }
324}
325
326#[async_trait]
327impl TableProvider for StreamTable {
328    fn schema(&self) -> SchemaRef {
329        Arc::clone(self.0.source.schema())
330    }
331
332    fn constraints(&self) -> Option<&Constraints> {
333        Some(&self.0.constraints)
334    }
335
336    fn table_type(&self) -> TableType {
337        TableType::Base
338    }
339
340    // Hand-written `#[async_trait]` expansion to reduce compile time. See
341    // <https://github.com/apache/datafusion/issues/13814#issuecomment-5292709677>
342    fn scan<'life0, 'life1, 'life2, 'life3, 'async_trait>(
343        &'life0 self,
344        state: &'life1 dyn Session,
345        projection: Option<&'life2 [usize]>,
346        filters: &'life3 [Expr],
347        limit: Option<usize>,
348    ) -> BoxFuture<'async_trait, Result<Arc<dyn ExecutionPlan>>>
349    where
350        'life0: 'async_trait,
351        'life1: 'async_trait,
352        'life2: 'async_trait,
353        'life3: 'async_trait,
354        Self: 'async_trait,
355    {
356        self.scan_boxed(state, projection, filters, limit)
357    }
358
359    // Hand-written `#[async_trait]` expansion to reduce compile time. See
360    // <https://github.com/apache/datafusion/issues/13814#issuecomment-5292709677>
361    fn insert_into<'life0, 'life1, 'async_trait>(
362        &'life0 self,
363        state: &'life1 dyn Session,
364        input: Arc<dyn ExecutionPlan>,
365        insert_op: InsertOp,
366    ) -> BoxFuture<'async_trait, Result<Arc<dyn ExecutionPlan>>>
367    where
368        'life0: 'async_trait,
369        'life1: 'async_trait,
370        Self: 'async_trait,
371    {
372        self.insert_into_boxed(state, input, insert_op)
373    }
374}
375
376impl StreamTable {
377    fn scan_boxed<'a>(
378        &'a self,
379        state: &'a dyn Session,
380        projection: Option<&'a [usize]>,
381        filters: &'a [Expr],
382        limit: Option<usize>,
383    ) -> BoxFuture<'a, Result<Arc<dyn ExecutionPlan>>> {
384        Box::pin(ready(self.scan_inner(state, projection, filters, limit)))
385    }
386
387    fn scan_inner(
388        &self,
389        state: &dyn Session,
390        projection: Option<&[usize]>,
391        _filters: &[Expr],
392        limit: Option<usize>,
393    ) -> Result<Arc<dyn ExecutionPlan>> {
394        let projected_schema = match projection {
395            Some(p) => {
396                let projected = Arc::new(self.0.source.schema().project(p)?);
397                create_lex_ordering(&projected, &self.0.order, state.execution_props())?
398            }
399            None => create_lex_ordering(
400                self.0.source.schema(),
401                &self.0.order,
402                state.execution_props(),
403            )?,
404        };
405
406        Ok(Arc::new(StreamingTableExec::try_new(
407            Arc::clone(self.0.source.schema()),
408            vec![Arc::new(StreamRead(Arc::clone(&self.0))) as _],
409            projection,
410            projected_schema,
411            true,
412            limit,
413        )?))
414    }
415
416    fn insert_into_boxed<'a>(
417        &'a self,
418        state: &'a dyn Session,
419        input: Arc<dyn ExecutionPlan>,
420        insert_op: InsertOp,
421    ) -> BoxFuture<'a, Result<Arc<dyn ExecutionPlan>>> {
422        Box::pin(ready(self.insert_into_inner(state, input, insert_op)))
423    }
424
425    fn insert_into_inner(
426        &self,
427        state: &dyn Session,
428        input: Arc<dyn ExecutionPlan>,
429        _insert_op: InsertOp,
430    ) -> Result<Arc<dyn ExecutionPlan>> {
431        let schema = self.0.source.schema();
432        let orders = create_lex_ordering(schema, &self.0.order, state.execution_props())?;
433        // It is sufficient to pass only one of the equivalent orderings:
434        let ordering = orders.into_iter().next().map(Into::into);
435
436        Ok(Arc::new(DataSinkExec::new(
437            input,
438            Arc::new(StreamWrite(Arc::clone(&self.0))),
439            ordering,
440        )))
441    }
442}
443
444#[derive(Debug)]
445struct StreamRead(Arc<StreamConfig>);
446
447impl PartitionStream for StreamRead {
448    fn schema(&self) -> &SchemaRef {
449        self.0.source.schema()
450    }
451
452    fn execute(&self, _ctx: Arc<TaskContext>) -> SendableRecordBatchStream {
453        let config = Arc::clone(&self.0);
454        let schema = Arc::clone(self.0.source.schema());
455        let mut builder = RecordBatchReceiverStreamBuilder::new(schema, 2);
456        let tx = builder.tx();
457        builder.spawn_blocking(move || {
458            let reader = config.reader()?;
459            for b in reader {
460                if tx.blocking_send(b.map_err(Into::into)).is_err() {
461                    break;
462                }
463            }
464            Ok(())
465        });
466        builder.build()
467    }
468}
469
470#[derive(Debug)]
471struct StreamWrite(Arc<StreamConfig>);
472
473impl DisplayAs for StreamWrite {
474    fn fmt_as(&self, t: DisplayFormatType, f: &mut Formatter) -> std::fmt::Result {
475        self.0.source.stream_write_display(t, f)
476    }
477}
478
479#[async_trait]
480impl DataSink for StreamWrite {
481    fn schema(&self) -> &SchemaRef {
482        self.0.source.schema()
483    }
484
485    // Hand-written `#[async_trait]` expansion to reduce compile time. See
486    // <https://github.com/apache/datafusion/issues/13814#issuecomment-5292709677>
487    fn write_all<'life0, 'life1, 'async_trait>(
488        &'life0 self,
489        data: SendableRecordBatchStream,
490        context: &'life1 Arc<TaskContext>,
491    ) -> BoxFuture<'async_trait, Result<u64>>
492    where
493        'life0: 'async_trait,
494        'life1: 'async_trait,
495        Self: 'async_trait,
496    {
497        self.write_all_boxed(data, context)
498    }
499}
500
501impl StreamWrite {
502    fn write_all_boxed<'a>(
503        &'a self,
504        data: SendableRecordBatchStream,
505        context: &'a Arc<TaskContext>,
506    ) -> BoxFuture<'a, Result<u64>> {
507        Box::pin(self.write_all_inner(data, context))
508    }
509
510    async fn write_all_inner(
511        &self,
512        mut data: SendableRecordBatchStream,
513        _context: &Arc<TaskContext>,
514    ) -> Result<u64> {
515        let config = Arc::clone(&self.0);
516        let (sender, mut receiver) = tokio::sync::mpsc::channel::<RecordBatch>(2);
517        // Note: FIFO Files support poll so this could use AsyncFd
518        let write_task = SpawnedTask::spawn_blocking(move || {
519            let mut count = 0_u64;
520            let mut writer = config.writer()?;
521            while let Some(batch) = receiver.blocking_recv() {
522                count += batch.num_rows() as u64;
523                writer.write(&batch)?;
524            }
525            Ok(count)
526        });
527
528        while let Some(b) = data.next().await.transpose()? {
529            if sender.send(b).await.is_err() {
530                break;
531            }
532        }
533        drop(sender);
534        write_task
535            .join_unwind()
536            .await
537            .map_err(|e| DataFusionError::ExecutionJoin(Box::new(e)))?
538    }
539}