1use std::collections::HashMap;
16use std::sync::Arc;
17
18use arrow::array::{Array, ArrayRef, AsArray, UInt64Array, make_array};
19use arrow::datatypes::DataType;
20use client::OutputData;
21use common_base::readable_size::ReadableSize;
22use common_datasource::file_format::Format;
23use common_datasource::file_format::csv::stream_to_csv;
24use common_datasource::file_format::json::stream_to_json;
25use common_datasource::file_format::parquet::stream_to_parquet;
26use common_datasource::object_store::{
27 LocalFileAccess, RemoteStorageAccess, build_backend_for_write_with_path,
28};
29use common_datasource::packed_writer::PackedTableWriter;
30use common_datasource::parquet_writer::ParquetFileWriter;
31use common_query::Output;
32use common_recordbatch::adapter::DfRecordBatchStreamAdapter;
33use common_recordbatch::{
34 SendableRecordBatchMapper, SendableRecordBatchStream, map_json_type_to_string,
35 map_json_type_to_string_schema,
36};
37use common_telemetry::{debug, tracing};
38use datafusion::datasource::DefaultTableSource;
39use datafusion_common::TableReference as DfTableReference;
40use datafusion_expr::LogicalPlanBuilder;
41use futures::StreamExt;
42use object_store::ObjectStore;
43use session::context::QueryContextRef;
44use snafu::{OptionExt, ResultExt, ensure};
45use table::TableRef;
46use table::requests::CopyTableRequest;
47use table::table::adapter::DfTableProviderAdapter;
48use table::table_reference::TableReference;
49use tokio_util::sync::CancellationToken;
50
51use crate::error::{self, BuildDfLogicalPlanSnafu, ExecLogicalPlanSnafu, Result};
52use crate::statement::StatementExecutor;
53use crate::statement::export_logical_tables::writers::ExportWriteBudget;
54use crate::statement::export_logical_tables::{
55 expand_export_batch, map_writer_error, rows_within_budget,
56};
57
58const WRITE_BUFFER_THRESHOLD: ReadableSize = ReadableSize::mb(8);
61
62const WRITE_CONCURRENCY: usize = 8;
64
65impl StatementExecutor {
66 async fn stream_to_file(
67 stream: SendableRecordBatchStream,
68 format: &Format,
69 object_store: ObjectStore,
70 path: &str,
71 ) -> Result<usize> {
72 let threshold = WRITE_BUFFER_THRESHOLD.as_bytes() as usize;
73
74 let stream = Box::pin(SendableRecordBatchMapper::new(
75 stream,
76 map_json_type_to_string,
77 map_json_type_to_string_schema,
78 ));
79 match format {
80 Format::Csv(format) => stream_to_csv(
81 Box::pin(DfRecordBatchStreamAdapter::new(stream)),
82 object_store,
83 path,
84 threshold,
85 WRITE_CONCURRENCY,
86 format,
87 )
88 .await
89 .context(error::WriteStreamToFileSnafu { path }),
90 Format::Json(format) => stream_to_json(
91 Box::pin(DfRecordBatchStreamAdapter::new(stream)),
92 object_store,
93 path,
94 threshold,
95 WRITE_CONCURRENCY,
96 format,
97 )
98 .await
99 .context(error::WriteStreamToFileSnafu { path }),
100 Format::Parquet(_) => stream_to_parquet(
101 Box::pin(DfRecordBatchStreamAdapter::new(stream)),
102 object_store,
103 path,
104 WRITE_CONCURRENCY,
105 )
106 .await
107 .context(error::WriteStreamToFileSnafu { path }),
108 _ => error::UnsupportedFormatSnafu {
109 format: format.clone(),
110 }
111 .fail(),
112 }
113 }
114
115 #[tracing::instrument(skip_all)]
116 pub(crate) async fn copy_table_to(
117 &self,
118 req: CopyTableRequest,
119 query_ctx: QueryContextRef,
120 ) -> Result<usize> {
121 let table_ref = TableReference::full(&req.catalog_name, &req.schema_name, &req.table_name);
122 let table = self.get_table(&table_ref).await?;
123 self.copy_captured_table_to(table, req, query_ctx).await
124 }
125
126 pub(crate) async fn copy_captured_table_to(
127 &self,
128 table: TableRef,
129 req: CopyTableRequest,
130 query_ctx: QueryContextRef,
131 ) -> Result<usize> {
132 self.copy_captured_table_to_managed(table, req, query_ctx, None, None)
133 .await
134 }
135
136 pub(crate) async fn copy_captured_table_to_managed(
137 &self,
138 table: TableRef,
139 req: CopyTableRequest,
140 query_ctx: QueryContextRef,
141 managed: Option<(&ExportWriteBudget, &CancellationToken)>,
142 packed: Option<PackedTableWriter>,
143 ) -> Result<usize> {
144 let info = table.table_info();
145 let table_ref = TableReference::full(&info.catalog_name, &info.schema_name, &info.name);
146 let table_id = info.table_id();
147 let format = Format::try_from(&req.with).context(error::ParseFileFormatSnafu)?;
148
149 let df_table_ref = DfTableReference::from(table_ref);
150
151 let filters = table
152 .schema()
153 .timestamp_column()
154 .and_then(|c| {
155 common_query::logical_plan::build_filter_from_timestamp(
156 &c.name,
157 req.timestamp_range.as_ref(),
158 )
159 })
160 .into_iter()
161 .collect::<Vec<_>>();
162
163 let table_provider = Arc::new(DfTableProviderAdapter::new(table));
164 let table_source = Arc::new(DefaultTableSource::new(table_provider));
165
166 let mut builder = LogicalPlanBuilder::scan_with_filters(
167 df_table_ref,
168 table_source,
169 None,
170 filters.clone(),
171 )
172 .context(BuildDfLogicalPlanSnafu)?;
173 for f in filters {
174 builder = builder.filter(f).context(BuildDfLogicalPlanSnafu)?;
175 }
176 if let Some(limit) = req.limit {
177 let fetch = usize::try_from(limit.min(i64::MAX as u64)).unwrap_or(usize::MAX);
179 builder = builder
180 .limit(0, Some(fetch))
181 .context(BuildDfLogicalPlanSnafu)?;
182 }
183 let plan = builder.build().context(BuildDfLogicalPlanSnafu)?;
184
185 let output = self
186 .query_engine
187 .execute(plan, query_ctx)
188 .await
189 .context(ExecLogicalPlanSnafu)?;
190
191 let CopyTableRequest {
192 location,
193 connection,
194 ..
195 } = &req;
196
197 debug!("Copy table: {table_id} to location: {location}");
198 Self::copy_to_file_managed(
199 &self.local_file_access,
200 &self.remote_storage_access,
201 &format,
202 output,
203 location,
204 connection,
205 managed,
206 packed,
207 )
208 .await
209 }
210
211 pub(crate) async fn copy_to_file(
212 &self,
213 format: &Format,
214 output: Output,
215 location: &str,
216 connection: &HashMap<String, String>,
217 ) -> Result<usize> {
218 Self::copy_to_file_managed(
219 &self.local_file_access,
220 &self.remote_storage_access,
221 format,
222 output,
223 location,
224 connection,
225 None,
226 None,
227 )
228 .await
229 }
230
231 #[allow(clippy::too_many_arguments)]
232 async fn copy_to_file_managed(
233 local_file_access: &LocalFileAccess,
234 remote_storage_access: &RemoteStorageAccess,
235 format: &Format,
236 output: Output,
237 location: &str,
238 connection: &HashMap<String, String>,
239 managed: Option<(&ExportWriteBudget, &CancellationToken)>,
240 packed: Option<PackedTableWriter>,
241 ) -> Result<usize> {
242 let output = if managed.is_none() {
243 output
244 .map_dictionary_to_values()
245 .context(error::BuildRecordBatchSnafu)?
246 } else {
247 output
248 };
249 let stream = match output.data {
250 OutputData::Stream(stream) => stream,
251 OutputData::RecordBatches(record_batches) => record_batches.as_stream(),
252 _ => unreachable!(),
253 };
254
255 if let (Some((budget, token)), Some(packed)) = (managed, packed) {
256 return stream_to_managed_parquet_with_packed(
257 stream,
258 ManagedParquetDestination::Packed(packed),
259 budget,
260 token,
261 )
262 .await;
263 }
264
265 let backend = build_backend_for_write_with_path(
266 location,
267 connection,
268 local_file_access,
269 remote_storage_access,
270 )
271 .await
272 .context(error::BuildBackendSnafu)?;
273 let filename = backend
274 .object_path
275 .with_context(|| error::UnexpectedSnafu {
276 violated: format!("Expected filename, path: {location}"),
277 })?;
278 if let Some((budget, token)) = managed {
279 stream_to_managed_parquet_with_packed(
280 stream,
281 ManagedParquetDestination::Object {
282 store: backend.object_store,
283 path: filename,
284 },
285 budget,
286 token,
287 )
288 .await
289 } else {
290 Self::stream_to_file(stream, format, backend.object_store, &filename).await
291 }
292 }
293}
294
295enum ManagedParquetDestination {
297 Object { store: ObjectStore, path: String },
298 Packed(PackedTableWriter),
299}
300
301#[cfg(test)]
302pub(crate) async fn stream_to_managed_parquet(
303 stream: SendableRecordBatchStream,
304 store: ObjectStore,
305 path: &str,
306 budget: &ExportWriteBudget,
307 token: &CancellationToken,
308) -> Result<usize> {
309 stream_to_managed_parquet_with_packed(
310 stream,
311 ManagedParquetDestination::Object {
312 store,
313 path: path.to_owned(),
314 },
315 budget,
316 token,
317 )
318 .await
319}
320
321async fn stream_to_managed_parquet_with_packed(
322 mut stream: SendableRecordBatchStream,
323 destination: ManagedParquetDestination,
324 budget: &ExportWriteBudget,
325 token: &CancellationToken,
326) -> Result<usize> {
327 use common_recordbatch::{RecordBatch, map_dictionary_to_values_schema};
328 let original = stream.schema();
329 let (expanded_schema, expand) = map_dictionary_to_values_schema(original.clone());
330 let json_columns = expanded_schema
331 .column_schemas()
332 .iter()
333 .enumerate()
334 .filter_map(|(index, column)| {
335 (column.data_type.is_json() && !column.data_type.is_json2()).then_some(index)
336 })
337 .collect::<Vec<_>>();
338 let (mapped_schema, json) = map_json_type_to_string_schema(expanded_schema.clone());
339 let output_schema = if json {
340 mapped_schema
341 } else {
342 expanded_schema.clone()
343 };
344 let packed_destination = matches!(destination, ManagedParquetDestination::Packed(_));
345 let schema = output_schema.arrow_schema().clone();
346 let (writer, path) = match destination {
347 ManagedParquetDestination::Packed(packed) => {
348 let path = packed.path().to_owned();
349 let limits =
350 crate::statement::export_logical_tables::LogicalTableExportLimits::default();
351 (
352 ParquetFileWriter::open_packed(schema, Some(limits.writer), packed),
353 path,
354 )
355 }
356 ManagedParquetDestination::Object { store, path } => (
357 ParquetFileWriter::open(schema, store, &path, 1, None).await,
358 path,
359 ),
360 };
361 let path = path.as_str();
362 let mut writer = writer.context(error::WriteStreamToFileSnafu { path })?;
363 let mut started = false;
364 let result = async {
365 let mut rows = 0;
366 loop {
367 let batch = tokio::select! {
368 biased;
369 _ = token.cancelled() => return error::LogicalTableExportCancelledSnafu.fail(),
370 batch = stream.next() => batch,
371 };
372 let Some(batch) = batch else { break };
373 let batch = batch
374 .context(error::BuildRecordBatchSnafu)?
375 .into_df_record_batch();
376 let mut offset = 0;
377 while offset < batch.num_rows() {
378 let (conversion, retained) =
381 ExportWriteBudget::conversion_budget(0, batch.num_columns(), usize::MAX)?;
382 let input = batch.clone();
383 let json_columns = json_columns.clone();
384 let (len, estimated) = common_runtime::spawn_blocking_global(move || {
385 rows_within_budget(&input, offset, input.num_rows(), conversion, &json_columns)
386 })
387 .await
388 .context(error::JoinTaskSnafu)??;
389 let reservation = retained.saturating_add(estimated.saturating_mul(4));
390 let permit = budget.reserve(reservation, token).await?;
391 let batch = batch.clone();
392 let (original, expanded_schema, output_schema) = (
393 original.clone(),
394 expanded_schema.clone(),
395 output_schema.clone(),
396 );
397 let (batch, len) = common_runtime::spawn_blocking_global(move || {
398 let mut batch = RecordBatch::from_df_record_batch(
399 original.clone(),
400 batch.slice(offset, len),
401 );
402 if expand {
403 batch = RecordBatch::from_df_record_batch(
404 expanded_schema.clone(),
405 expand_export_batch(
406 &batch.into_df_record_batch(),
407 expanded_schema.arrow_schema().clone(),
408 )?,
409 );
410 }
411 if json {
412 batch = map_json_type_to_string(batch, &expanded_schema, &output_schema)
413 .context(error::BuildRecordBatchSnafu)?;
414 }
415 let mut batch = batch.into_df_record_batch();
416 if batch.get_array_memory_size() > reservation {
417 let indices = UInt64Array::from_iter_values(0..batch.num_rows() as u64);
418 batch = arrow::compute::take_record_batch(&batch, &indices)
419 .context(error::ComputeArrowSnafu)?;
420 let arrays = batch
421 .columns()
422 .iter()
423 .map(compact_view_buffers)
424 .collect::<Result<Vec<_>>>()?;
425 batch = arrow::record_batch::RecordBatch::try_new(batch.schema(), arrays)
426 .context(error::ComputeArrowSnafu)?;
427 }
428 ensure!(
429 batch.get_array_memory_size() <= reservation,
430 error::LogicalTableExportResourceSnafu {
431 reason: "converted backing buffers exceed reservation"
432 }
433 );
434 Ok::<_, error::Error>((batch, len))
435 })
436 .await
437 .context(error::JoinTaskSnafu)??;
438 started = true;
439 let write = writer.write(batch, Some(token)).await;
440 drop(permit);
441 write.map_err(|error| map_writer_error(error, path))?;
442 rows += len;
443 offset += len;
444 }
445 }
446 started = true;
447 writer
448 .finish(Some(token))
449 .await
450 .map_err(|error| map_writer_error(error, path))?;
451 Ok(rows)
452 }
453 .await;
454 if result.is_err() {
455 token.cancel();
456 if (started || packed_destination)
457 && let Err(error) = writer.abort().await
458 {
459 common_telemetry::warn!(error; "Failed to abort ordinary export file");
460 }
461 }
462 result
463}
464
465fn compact_view_buffers(array: &ArrayRef) -> Result<ArrayRef> {
468 match array.data_type() {
469 DataType::Utf8View => Ok(Arc::new(array.as_string_view().gc())),
470 DataType::BinaryView => Ok(Arc::new(array.as_binary_view().gc())),
471 _ => {
472 let data = array.to_data();
473 if data.child_data().is_empty() {
474 return Ok(array.clone());
475 }
476 let children = data
477 .child_data()
478 .iter()
479 .map(|child| {
480 compact_view_buffers(&make_array(child.clone())).map(|array| array.to_data())
481 })
482 .collect::<Result<Vec<_>>>()?;
483 Ok(make_array(
484 data.into_builder()
485 .child_data(children)
486 .build()
487 .context(error::ComputeArrowSnafu)?,
488 ))
489 }
490 }
491}
492
493#[cfg(test)]
494mod tests {
495 use arrow::array::{
496 ArrayRef, BinaryArray, BinaryViewArray, DictionaryArray, Int32Array, StringArray,
497 StringViewArray,
498 };
499 use arrow::datatypes::Int32Type;
500 use common_recordbatch::{RecordBatch, RecordBatches};
501 use datafusion::parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
502 use datatypes::prelude::ConcreteDataType;
503 use datatypes::schema::{ColumnSchema, Schema};
504
505 use super::*;
506
507 #[tokio::test]
508 async fn managed_packed_copy_uses_shared_backend_and_stream_error_label() {
509 use common_datasource::packed_writer::PackedWriter;
510
511 let directory = common_test_util::temp_dir::create_temp_dir("managed_packed_copy");
512 let location = url::Url::from_directory_path(directory.path()).unwrap();
513 let access = LocalFileAccess::sandboxed(directory.path()).unwrap();
514 let store = object_store::secure_fs::SecureFsRoot::open(directory.path())
515 .unwrap()
516 .build_operator();
517 let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
518 "value",
519 ConcreteDataType::int32_datatype(),
520 false,
521 )]));
522 let output = |invalid_schema| {
523 let values: ArrayRef = if invalid_schema {
524 Arc::new(StringArray::from(vec!["a", "b", "c"]))
525 } else {
526 Arc::new(Int32Array::from(vec![1, 2, 3]))
527 };
528 let batch =
529 arrow::record_batch::RecordBatch::try_from_iter([("value", values)]).unwrap();
530 let stream = datafusion::physical_plan::stream::RecordBatchStreamAdapter::new(
531 schema.arrow_schema().clone(),
532 futures::stream::iter([Ok(batch)]),
533 );
534 let stream =
535 common_recordbatch::adapter::RecordBatchStreamAdapter::try_new(Box::pin(stream))
536 .unwrap();
537 Output::new_with_stream(Box::pin(stream))
538 };
539 let format = Format::Parquet(Default::default());
540 let connection = HashMap::new();
541 let budget = ExportWriteBudget::new(1);
542 let token = CancellationToken::new();
543 let result = StatementExecutor::copy_to_file_managed(
544 &access,
545 &RemoteStorageAccess::unrestricted(),
546 &format,
547 output(false),
548 location.as_str(),
549 &connection,
550 Some((&budget, &token)),
551 None,
552 )
553 .await;
554 assert!(matches!(
555 result,
556 Err(error::Error::BuildBackend {
557 source: common_datasource::error::Error::MissingObjectName { .. },
558 ..
559 })
560 ));
561
562 for (id, invalid_schema) in [(42, false), (43, true)] {
563 let shared = PackedWriter::new(store.clone()).unwrap();
564 let packed = PackedTableWriter::new(shared, "audit".into(), id, true);
565 let token = CancellationToken::new();
566 let result = StatementExecutor::copy_to_file_managed(
567 &access,
568 &RemoteStorageAccess::unrestricted(),
569 &format,
570 output(invalid_schema),
571 location.as_str(),
572 &connection,
573 Some((&budget, &token)),
574 Some(packed),
575 )
576 .await;
577 let path = format!("table-{id}.parquet");
578 if invalid_schema {
579 let error::Error::WriteStreamToFile {
580 path: actual,
581 source,
582 ..
583 } = result.unwrap_err()
584 else {
585 panic!("expected stream write error");
586 };
587 assert_eq!(actual, path);
588 assert!(
589 matches!(source, common_datasource::error::Error::WriteParquet { path: actual, .. } if actual == path)
590 );
591 assert!(!store.exists(&path).await.unwrap());
592 } else {
593 assert_eq!(result.unwrap(), 3);
594 let reader = ParquetRecordBatchReaderBuilder::try_new(
595 store.read(&path).await.unwrap().to_bytes(),
596 )
597 .unwrap();
598 assert_eq!(reader.metadata().file_metadata().num_rows(), 3);
599 }
600 }
601 }
602
603 #[tokio::test]
604 async fn managed_copy_preserves_existing_file_before_sink_open() {
605 let temp_dir = common_test_util::temp_dir::create_temp_dir("managed_copy_existing_file");
606 let store = object_store::secure_fs::SecureFsRoot::open(temp_dir.path())
607 .unwrap()
608 .build_operator();
609 let path = "existing.parquet";
610 store.write(path, "original").await.unwrap();
611 let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
612 "value",
613 ConcreteDataType::int32_datatype(),
614 false,
615 )]));
616 let batch = arrow::record_batch::RecordBatch::try_new(
617 schema.arrow_schema().clone(),
618 vec![Arc::new(Int32Array::from(vec![1]))],
619 )
620 .unwrap();
621 let batches = async_stream::stream! {
622 yield Ok(batch);
623 yield Err(datafusion::error::DataFusionError::Execution("source failed".into()));
624 };
625 let stream = datafusion::physical_plan::stream::RecordBatchStreamAdapter::new(
626 schema.arrow_schema().clone(),
627 batches,
628 );
629 let stream =
630 common_recordbatch::adapter::RecordBatchStreamAdapter::try_new(Box::pin(stream))
631 .unwrap();
632
633 let result = stream_to_managed_parquet(
634 Box::pin(stream),
635 store.clone(),
636 path,
637 &ExportWriteBudget::new(1),
638 &CancellationToken::new(),
639 )
640 .await;
641
642 assert!(result.is_err());
643 assert_eq!(
644 store.read(path).await.unwrap().to_bytes().as_ref(),
645 b"original"
646 );
647 }
648
649 #[tokio::test]
650 async fn managed_copy_rechunks_large_backing_buffers() {
651 let value = "x".repeat(9 * 1024);
652 for view in [false, true] {
653 let data_type = if view {
654 ConcreteDataType::utf8_view_datatype()
655 } else {
656 ConcreteDataType::string_datatype()
657 };
658 let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
659 "value", data_type, false,
660 )]));
661 let values = vec![value.as_str(); 8192];
662 let array: ArrayRef = if view {
663 Arc::new(StringViewArray::from(values))
664 } else {
665 Arc::new(StringArray::from(values))
666 };
667 let batch = arrow::record_batch::RecordBatch::try_new(
668 schema.arrow_schema().clone(),
669 vec![array],
670 )
671 .unwrap();
672 assert!(batch.get_array_memory_size() > 64 * 1024 * 1024);
673 for input in [batch.clone(), batch.slice(200, 3)] {
675 let rows = input.num_rows();
676 let batches = RecordBatches::try_new(
677 schema.clone(),
678 vec![RecordBatch::from_df_record_batch(schema.clone(), input)],
679 )
680 .unwrap();
681 let store = ObjectStore::new(object_store::services::Memory::default()).unwrap();
682 let budget = ExportWriteBudget::new(1);
683 assert_eq!(
684 stream_to_managed_parquet(
685 batches.as_stream(),
686 store.clone(),
687 "large.parquet",
688 &budget,
689 &CancellationToken::new(),
690 )
691 .await
692 .unwrap(),
693 rows
694 );
695 let reader = ParquetRecordBatchReaderBuilder::try_new(
696 store.read("large.parquet").await.unwrap().to_bytes(),
697 )
698 .unwrap()
699 .build()
700 .unwrap();
701 let mut actual_rows = 0;
702 for batch in reader {
703 let batch = batch.unwrap();
704 let strings = arrow::compute::cast(batch.column(0), &DataType::Utf8).unwrap();
705 assert!(
706 strings
707 .as_string::<i32>()
708 .iter()
709 .all(|item| item == Some(value.as_str()))
710 );
711 actual_rows += batch.num_rows();
712 }
713 assert_eq!(actual_rows, rows);
714 assert_eq!(budget.available(), (1, 64 * 1024 * 1024));
715 }
716 }
717 }
718
719 #[tokio::test]
720 async fn managed_copy_preserves_dictionary_json_views_and_empty_schema() {
721 let schema = Arc::new(Schema::new(vec![
722 ColumnSchema::new(
723 "host",
724 ConcreteDataType::dictionary_datatype(
725 ConcreteDataType::int32_datatype(),
726 ConcreteDataType::string_datatype(),
727 ),
728 true,
729 ),
730 ColumnSchema::new("json", ConcreteDataType::json_datatype(), true),
731 ColumnSchema::new("text_view", ConcreteDataType::utf8_view_datatype(), true),
732 ColumnSchema::new(
733 "binary_view",
734 ConcreteDataType::binary_view_datatype(),
735 true,
736 ),
737 ]));
738 let dictionary = DictionaryArray::<Int32Type>::new(
739 Int32Array::from(vec![Some(0), None, Some(1), Some(1)]),
740 Arc::new(StringArray::from(vec!["tag", &"x".repeat(3 * 1024 * 1024)])),
741 );
742 let json = datatypes::types::parse_string_to_jsonb(&format!(
743 r#"{{"value":"escaped\ntext{}","n":123456789}}"#,
744 "y".repeat(160_000)
745 ))
746 .unwrap();
747 let arrays = vec![
748 Arc::new(dictionary) as ArrayRef,
749 Arc::new(BinaryArray::from(vec![
750 Some(json.as_slice()),
751 None,
752 None,
753 Some(json.as_slice()),
754 ])),
755 Arc::new(StringViewArray::from(vec![
756 Some("short"),
757 None,
758 Some("long view"),
759 Some("long view"),
760 ])),
761 Arc::new(BinaryViewArray::from(vec![
762 Some(&b"short"[..]),
763 None,
764 Some(&b"long view"[..]),
765 Some(&b"long view"[..]),
766 ])),
767 ];
768 let batch =
769 arrow::record_batch::RecordBatch::try_new(schema.arrow_schema().clone(), arrays)
770 .unwrap();
771 let batch = RecordBatch::from_df_record_batch(schema.clone(), batch);
772 for empty in [false, true] {
773 let batches = RecordBatches::try_new(
774 schema.clone(),
775 if empty { vec![] } else { vec![batch.clone()] },
776 )
777 .unwrap();
778 let store = ObjectStore::new(object_store::services::Memory::default()).unwrap();
779 let budget = ExportWriteBudget::new(1);
780 let token = CancellationToken::new();
781 let managed = stream_to_managed_parquet(
782 batches.as_stream(),
783 store.clone(),
784 "managed.parquet",
785 &budget,
786 &token,
787 )
788 .await
789 .unwrap();
790 let output = Output::new_with_record_batches(batches)
791 .map_dictionary_to_values()
792 .unwrap();
793 let OutputData::RecordBatches(batches) = output.data else {
794 panic!("expected batches");
795 };
796 let stream = SendableRecordBatchMapper::new(
797 batches.as_stream(),
798 map_json_type_to_string,
799 map_json_type_to_string_schema,
800 );
801 let ordinary = stream_to_parquet(
802 Box::pin(DfRecordBatchStreamAdapter::new(Box::pin(stream))),
803 store.clone(),
804 "ordinary.parquet",
805 WRITE_CONCURRENCY,
806 )
807 .await
808 .unwrap();
809 assert_eq!(managed, ordinary);
810 let mut outputs = Vec::new();
811 for name in ["managed.parquet", "ordinary.parquet"] {
812 let reader = ParquetRecordBatchReaderBuilder::try_new(
813 store.read(name).await.unwrap().to_bytes(),
814 )
815 .unwrap();
816 let schema = reader.schema().clone();
817 let values = reader
818 .build()
819 .unwrap()
820 .collect::<std::result::Result<Vec<_>, _>>()
821 .unwrap();
822 outputs.push((schema, values));
823 }
824 assert_eq!(outputs[0], outputs[1]);
825 assert_eq!(budget.available(), (1, 64 * 1024 * 1024));
826 }
827 }
828}