Skip to main content

common_datasource/
file_format.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15pub mod csv;
16pub mod decimal;
17pub mod json;
18pub mod orc;
19pub mod parquet;
20#[cfg(test)]
21pub mod tests;
22
23pub const DEFAULT_SCHEMA_INFER_MAX_RECORD: usize = 1000;
24
25use std::collections::HashMap;
26use std::result;
27use std::sync::Arc;
28use std::task::Poll;
29
30use arrow::record_batch::RecordBatch;
31use arrow_schema::{ArrowError, Schema as ArrowSchema};
32use async_trait::async_trait;
33use bytes::{Buf, Bytes};
34use common_recordbatch::DfSendableRecordBatchStream;
35use datafusion::datasource::file_format::file_compression_type::FileCompressionType as DfCompressionType;
36use datafusion::datasource::listing::PartitionedFile;
37use datafusion::datasource::object_store::ObjectStoreUrl;
38use datafusion::datasource::physical_plan::{
39    FileGroup, FileOpenFuture, FileScanConfigBuilder, FileSource, FileStreamBuilder,
40};
41use datafusion::error::{DataFusionError, Result as DataFusionResult};
42use datafusion::physical_plan::SendableRecordBatchStream;
43use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
44use futures::{StreamExt, TryStreamExt};
45use object_store::ObjectStore;
46use snafu::ResultExt;
47use tokio::io::AsyncWriteExt;
48use tokio_util::compat::FuturesAsyncWriteCompatExt;
49
50use self::csv::CsvFormat;
51use self::json::JsonFormat;
52use self::orc::OrcFormat;
53use self::parquet::ParquetFormat;
54use crate::DEFAULT_WRITE_BUFFER_SIZE;
55use crate::buffered_writer::DfRecordBatchEncoder;
56use crate::compressed_writer::{CompressedWriter, IntoCompressedWriter};
57use crate::compression::CompressionType;
58use crate::error::{self, Result};
59use crate::share_buffer::SharedBuffer;
60
61pub const FORMAT_COMPRESSION_TYPE: &str = "compression_type";
62pub const FORMAT_DELIMITER: &str = "delimiter";
63pub const FORMAT_SCHEMA_INFER_MAX_RECORD: &str = "schema_infer_max_record";
64pub const FORMAT_HEADERS: &str = "headers";
65pub const FORMAT_HAS_HEADER: &str = "has_header";
66pub const FORMAT_SKIP_BAD_RECORDS: &str = "skip_bad_records";
67pub const FORMAT_STRICT_HEADERS: &str = "strict_headers";
68pub const FORMAT_TYPE: &str = "format";
69pub const FILE_PATTERN: &str = "pattern";
70pub const TIMESTAMP_FORMAT: &str = "timestamp_format";
71pub const TIME_FORMAT: &str = "time_format";
72pub const DATE_FORMAT: &str = "date_format";
73
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub enum Format {
76    Csv(CsvFormat),
77    Json(JsonFormat),
78    Parquet(ParquetFormat),
79    Orc(OrcFormat),
80}
81
82impl Format {
83    pub fn suffix(&self) -> &'static str {
84        match self {
85            Format::Csv(_) => ".csv",
86            Format::Json(_) => ".json",
87            Format::Parquet(_) => ".parquet",
88            &Format::Orc(_) => ".orc",
89        }
90    }
91}
92
93impl TryFrom<&HashMap<String, String>> for Format {
94    type Error = error::Error;
95
96    fn try_from(options: &HashMap<String, String>) -> Result<Self> {
97        let format = options
98            .get(FORMAT_TYPE)
99            .map(|format| format.to_ascii_uppercase())
100            .unwrap_or_else(|| "PARQUET".to_string());
101
102        match format.as_str() {
103            "CSV" => Ok(Self::Csv(CsvFormat::try_from(options)?)),
104            "JSON" => Ok(Self::Json(JsonFormat::try_from(options)?)),
105            "PARQUET" => Ok(Self::Parquet(ParquetFormat::default())),
106            "ORC" => Ok(Self::Orc(OrcFormat)),
107            _ => error::UnsupportedFormatSnafu { format: &format }.fail(),
108        }
109    }
110}
111
112#[async_trait]
113pub trait FileFormat: Send + Sync + std::fmt::Debug {
114    async fn infer_schema(&self, store: &ObjectStore, path: &str) -> Result<ArrowSchema>;
115}
116
117pub trait ArrowDecoder: Send + 'static {
118    /// Decode records from `buf` returning the number of bytes read.
119    ///
120    /// This method returns `Ok(0)` once `batch_size` objects have been parsed since the
121    /// last call to [`Self::flush`], or `buf` is exhausted.
122    ///
123    /// Any remaining bytes should be included in the next call to [`Self::decode`].
124    fn decode(&mut self, buf: &[u8]) -> result::Result<usize, ArrowError>;
125
126    /// Flushes the currently buffered data to a [`RecordBatch`].
127    ///
128    /// This should only be called after [`Self::decode`] has returned `Ok(0)`,
129    /// otherwise may return an error if part way through decoding a record
130    ///
131    /// Returns `Ok(None)` if no buffered data.
132    fn flush(&mut self) -> result::Result<Option<RecordBatch>, ArrowError>;
133}
134
135impl ArrowDecoder for arrow::csv::reader::Decoder {
136    fn decode(&mut self, buf: &[u8]) -> result::Result<usize, ArrowError> {
137        self.decode(buf)
138    }
139
140    fn flush(&mut self) -> result::Result<Option<RecordBatch>, ArrowError> {
141        self.flush()
142    }
143}
144
145impl ArrowDecoder for arrow::json::reader::Decoder {
146    fn decode(&mut self, buf: &[u8]) -> result::Result<usize, ArrowError> {
147        self.decode(buf)
148    }
149
150    fn flush(&mut self) -> result::Result<Option<RecordBatch>, ArrowError> {
151        self.flush()
152    }
153}
154
155pub fn open_with_decoder<T: ArrowDecoder, F: Fn() -> DataFusionResult<T>>(
156    object_store: Arc<ObjectStore>,
157    path: String,
158    compression_type: CompressionType,
159    decoder_factory: F,
160) -> DataFusionResult<FileOpenFuture> {
161    let mut decoder = decoder_factory()?;
162    Ok(Box::pin(async move {
163        let reader = object_store
164            .reader(&path)
165            .await
166            .map_err(|e| DataFusionError::External(Box::new(e)))?
167            .into_bytes_stream(..)
168            .await
169            .map_err(|e| DataFusionError::External(Box::new(e)))?;
170
171        let mut upstream = compression_type.convert_stream(reader).fuse();
172
173        let mut buffered = Bytes::new();
174
175        let stream = futures::stream::poll_fn(move |cx| {
176            loop {
177                if buffered.is_empty()
178                    && let Some(result) = futures::ready!(upstream.poll_next_unpin(cx))
179                {
180                    buffered = result?;
181                }
182
183                let decoded = decoder.decode(buffered.as_ref())?;
184
185                if decoded == 0 {
186                    break;
187                } else {
188                    buffered.advance(decoded);
189                }
190            }
191
192            Poll::Ready(decoder.flush().transpose())
193        });
194
195        Ok(stream.map_err(Into::into).boxed())
196    }))
197}
198
199pub async fn infer_schemas(
200    store: &ObjectStore,
201    files: &[String],
202    file_format: &dyn FileFormat,
203) -> Result<ArrowSchema> {
204    let mut schemas = Vec::with_capacity(files.len());
205    for file in files {
206        schemas.push(file_format.infer_schema(store, file).await?)
207    }
208    ArrowSchema::try_merge(schemas).context(error::MergeSchemaSnafu)
209}
210
211/// Writes data to a compressed writer if the data is not empty.
212///
213/// Does nothing if `data` is empty; otherwise writes all data and returns any error.
214async fn write_to_compressed_writer(
215    compressed_writer: &mut CompressedWriter,
216    data: &[u8],
217) -> Result<()> {
218    if !data.is_empty() {
219        compressed_writer
220            .write_all(data)
221            .await
222            .context(error::AsyncWriteSnafu)?;
223    }
224    Ok(())
225}
226
227/// Streams [SendableRecordBatchStream] to a file with optional compression support.
228/// Data is buffered and flushed according to the given `threshold`.
229/// Ensures that writer resources are cleanly released and that an empty file is not
230/// created if no rows are written.
231///
232/// Returns the total number of rows successfully written.
233pub async fn stream_to_file<E>(
234    mut stream: SendableRecordBatchStream,
235    store: ObjectStore,
236    path: &str,
237    threshold: usize,
238    concurrency: usize,
239    compression_type: CompressionType,
240    encoder_factory: impl Fn(SharedBuffer) -> E,
241) -> Result<usize>
242where
243    E: DfRecordBatchEncoder,
244{
245    // Create the file writer with OpenDAL's built-in buffering
246    let writer = store
247        .writer_with(path)
248        .concurrent(concurrency)
249        .chunk(DEFAULT_WRITE_BUFFER_SIZE.as_bytes() as usize)
250        .await
251        .with_context(|_| error::WriteObjectSnafu { path })?
252        .into_futures_async_write()
253        .compat_write();
254
255    // Apply compression if needed
256    let mut compressed_writer = writer.into_compressed_writer(compression_type);
257
258    // Create a buffer for the encoder
259    let buffer = SharedBuffer::with_capacity(threshold);
260    let mut encoder = encoder_factory(buffer.clone());
261
262    let mut rows = 0;
263
264    // Process each record batch
265    while let Some(batch) = stream.next().await {
266        let batch = batch.context(error::ReadRecordBatchSnafu)?;
267
268        // Write batch using the encoder
269        encoder.write(&batch)?;
270        rows += batch.num_rows();
271
272        loop {
273            let chunk = {
274                let mut buffer_guard = buffer.buffer.lock().unwrap();
275                if buffer_guard.len() < threshold {
276                    break;
277                }
278                buffer_guard.split_to(threshold)
279            };
280            write_to_compressed_writer(&mut compressed_writer, &chunk).await?;
281        }
282    }
283
284    // If no row's been written, just simply close the underlying writer
285    // without flush so that no file will be actually created.
286    if rows != 0 {
287        // Final flush of any remaining data
288        let final_data = {
289            let mut buffer_guard = buffer.buffer.lock().unwrap();
290            buffer_guard.split()
291        };
292        write_to_compressed_writer(&mut compressed_writer, &final_data).await?;
293    }
294
295    // Shutdown compression and close writer
296    compressed_writer.shutdown().await?;
297
298    Ok(rows)
299}
300
301/// Creates a [FileStream] for reading data from a file with optional column projection
302/// and compression support.
303///
304/// Returns [SendableRecordBatchStream].
305pub async fn file_to_stream(
306    store: &ObjectStore,
307    filename: &str,
308    file_source: Arc<dyn FileSource>,
309    projection: Option<Vec<usize>>,
310    compression_type: CompressionType,
311) -> Result<DfSendableRecordBatchStream> {
312    let df_compression: DfCompressionType = compression_type.into();
313    let config =
314        FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), file_source.clone())
315            .with_file_group(FileGroup::new(vec![PartitionedFile::new(
316                filename.to_string(),
317                0,
318            )]))
319            .with_projection_indices(projection)?
320            .with_file_compression_type(df_compression)
321            .build();
322
323    let store = Arc::new(object_store_opendal::OpendalStore::new(store.clone()));
324    let file_opener = config.file_source().create_file_opener(store, &config, 0)?;
325    let stream = FileStreamBuilder::new(&config)
326        .with_partition(0)
327        .with_file_opener(file_opener)
328        .with_metrics(&ExecutionPlanMetricsSet::new())
329        .build()?;
330
331    Ok(Box::pin(stream))
332}