common_datasource/
file_format.rs1pub 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 fn decode(&mut self, buf: &[u8]) -> result::Result<usize, ArrowError>;
125
126 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
211async 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
227pub 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 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 let mut compressed_writer = writer.into_compressed_writer(compression_type);
257
258 let buffer = SharedBuffer::with_capacity(threshold);
260 let mut encoder = encoder_factory(buffer.clone());
261
262 let mut rows = 0;
263
264 while let Some(batch) = stream.next().await {
266 let batch = batch.context(error::ReadRecordBatchSnafu)?;
267
268 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 rows != 0 {
287 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 compressed_writer.shutdown().await?;
297
298 Ok(rows)
299}
300
301pub 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}