1pub(crate) mod writers;
23
24use std::collections::{BTreeMap, BTreeSet, HashMap};
25use std::sync::Arc;
26
27use arrow::array::{Array, ArrayRef, AsArray, ListArray, StructArray, UInt32Array};
28use arrow::buffer::OffsetBuffer;
29use arrow::compute::{cast, take};
30use arrow::datatypes::{DataType, SchemaRef};
31use arrow::downcast_dictionary_array;
32use arrow::record_batch::RecordBatch;
33use common_datasource::object_store::{
34 LocalFileAccess, RemoteStorageAccess, build_backend_for_write,
35};
36use common_datasource::packed_writer::{PackedTableWriter, PackedWriterRef};
37use common_datasource::parquet_writer::{
38 ParquetCreationPolicy, ParquetFileWriter, ParquetWriterLimits,
39};
40use common_meta::key::table_route::{TableRouteManager, TableRouteValue};
41use common_query::OutputData;
42use common_recordbatch::SendableRecordBatchStream;
43use common_time::range::TimestampRange;
44use datafusion::datasource::DefaultTableSource;
45use datafusion_common::TableReference as DfTableReference;
46use datafusion_expr::{LogicalPlan, LogicalPlanBuilder, col, lit};
47use futures::StreamExt;
48use object_store::ObjectStore;
49use session::context::QueryContextRef;
50use snafu::{IntoError, OptionExt, ResultExt, ensure};
51use store_api::metric_engine_consts::{
52 DATA_SCHEMA_TABLE_ID_COLUMN_NAME as TABLE_ID, DATA_SCHEMA_TSID_COLUMN_NAME as TSID,
53 LOGICAL_TABLE_METADATA_KEY, METRIC_ENGINE_NAME, PHYSICAL_TABLE_METADATA_KEY,
54};
55use table::TableRef;
56use table::metadata::TableId;
57use table::table::adapter::DfTableProviderAdapter;
58use tokio::sync::OwnedSemaphorePermit;
59use tokio_util::sync::CancellationToken;
60
61use crate::error::{self, InvalidLogicalTableExportSnafu, LogicalTableExportResourceSnafu, Result};
62use crate::statement::StatementExecutor;
63use crate::statement::database_copy::DatabaseExportFile;
64use crate::statement::export_logical_tables::writers::{ExportWriteBudget, Payload, TableWriters};
65
66#[derive(Clone, Copy, Debug)]
70pub struct LogicalTableExportLimits {
71 pub input_batch_bytes: usize,
73 pub conversion_bytes: usize,
75 pub writer: ParquetWriterLimits,
77}
78
79impl Default for LogicalTableExportLimits {
80 fn default() -> Self {
81 Self {
82 input_batch_bytes: 64 * 1024 * 1024,
83 conversion_bytes: 1024 * 1024,
84 writer: ParquetWriterLimits {
85 row_group_rows: 1024 * 1024,
86 flush_threshold_bytes: 8 * 1024 * 1024,
87 max_row_groups: 4096,
88 },
89 }
90 }
91}
92
93impl LogicalTableExportLimits {
94 fn validate(self) -> Result<()> {
95 ensure!(
96 self.input_batch_bytes > 0 && self.conversion_bytes > 0,
97 InvalidLogicalTableExportSnafu {
98 reason: "export limits must be positive"
99 }
100 );
101 Ok(())
102 }
103}
104
105pub struct LogicalTableExport {
109 physical_table: TableRef,
110 scan_projection: Vec<usize>,
111 logical_tables: BTreeMap<TableId, LogicalTableProjection>,
112}
113
114pub(crate) struct LogicalTableProjection {
115 name: String,
116 output: DatabaseExportFile,
117 schema: SchemaRef,
118 projection: Vec<usize>,
119}
120
121impl LogicalTableExport {
122 pub fn try_new(physical: TableRef, tables: &[TableRef]) -> Result<Self> {
125 Self::try_new_in_directory(physical, tables, "")
126 }
127
128 pub(crate) fn try_new_in_directory(
129 physical: TableRef,
130 tables: &[TableRef],
131 directory: &str,
132 ) -> Result<Self> {
133 let physical_info = physical.table_info();
134 ensure!(
135 physical_info.meta.engine == METRIC_ENGINE_NAME
136 && physical_info
137 .meta
138 .options
139 .extra_options
140 .contains_key(PHYSICAL_TABLE_METADATA_KEY)
141 && !tables.is_empty(),
142 InvalidLogicalTableExportSnafu {
143 reason: "expected a Metric physical table and selected logical tables"
144 }
145 );
146 let physical_schema = physical.schema();
147 let id_index = physical_schema.column_index_by_name(TABLE_ID).context(
148 InvalidLogicalTableExportSnafu {
149 reason: "physical schema has no __table_id",
150 },
151 )?;
152 let mut scan_projection = BTreeSet::from([id_index]);
153 let mut logical_tables = BTreeMap::new();
154 for table in tables {
155 let info = table.table_info();
156 let name = &info.name;
157 ensure!(
158 info.catalog_name == physical_info.catalog_name
159 && info.schema_name == physical_info.schema_name
160 && info.meta.engine == METRIC_ENGINE_NAME
161 && info
162 .meta
163 .options
164 .extra_options
165 .contains_key(LOGICAL_TABLE_METADATA_KEY),
166 InvalidLogicalTableExportSnafu {
167 reason: format!(
168 "{name} is not a Metric logical table in the physical table schema"
169 )
170 }
171 );
172 let schema = table.schema().arrow_schema().clone();
173 let indices = schema
174 .fields()
175 .iter()
176 .map(|field| {
177 ensure!(
178 field.name() != TABLE_ID && field.name() != TSID,
179 InvalidLogicalTableExportSnafu {
180 reason: "logical schema contains internal Metric columns"
181 }
182 );
183 let index = physical_schema
184 .column_index_by_name(field.name())
185 .with_context(|| InvalidLogicalTableExportSnafu {
186 reason: format!("physical schema lacks {}", field.name()),
187 })?;
188 ensure!(
189 physical_schema.arrow_schema().field(index).data_type()
190 == field.data_type(),
191 InvalidLogicalTableExportSnafu {
192 reason: format!("physical/logical type mismatch for {}", field.name())
193 }
194 );
195 Ok(index)
196 })
197 .collect::<Result<Vec<_>>>()?;
198 scan_projection.extend(indices.iter().copied());
199 ensure!(
200 logical_tables
201 .insert(
202 info.table_id(),
203 LogicalTableProjection {
204 name: name.clone(),
205 output: DatabaseExportFile::new(directory, name, ".parquet")?,
206 schema,
207 projection: indices,
208 }
209 )
210 .is_none(),
211 InvalidLogicalTableExportSnafu {
212 reason: "duplicate logical table"
213 }
214 );
215 }
216 let scan_projection = scan_projection.into_iter().collect::<Vec<_>>();
217 for file in logical_tables.values_mut() {
218 for index in &mut file.projection {
219 *index = scan_projection.binary_search(index).map_err(|_| {
220 error::UnexpectedSnafu {
221 violated: "logical column missing from physical projection",
222 }
223 .build()
224 })?;
225 }
226 }
227 Ok(Self {
228 physical_table: physical,
229 scan_projection,
230 logical_tables,
231 })
232 }
233
234 pub(crate) fn output_files(&self) -> impl Iterator<Item = &DatabaseExportFile> {
235 self.logical_tables.values().map(|table| &table.output)
236 }
237
238 async fn validate_table_routes(&self, manager: &TableRouteManager) -> Result<()> {
239 let table_ids = self.logical_tables.keys().copied().collect::<Vec<_>>();
240 let routes = manager
241 .table_route_storage()
242 .batch_get(&table_ids)
243 .await
244 .context(error::TableMetadataManagerSnafu)?;
245 let physical_table_id = self.physical_table.table_info().table_id();
246 for (table_id, route) in table_ids.into_iter().zip(routes) {
247 ensure!(
248 matches!(route, Some(TableRouteValue::Logical(route)) if route.physical_table_id() == physical_table_id),
249 InvalidLogicalTableExportSnafu {
250 reason: format!(
251 "logical table {table_id} does not belong to physical table {physical_table_id}"
252 )
253 }
254 );
255 }
256 Ok(())
257 }
258
259 fn build_plan(&self, time_range: Option<&TimestampRange>) -> Result<LogicalPlan> {
260 let info = self.physical_table.table_info();
261 let mut filters = self
262 .physical_table
263 .schema()
264 .timestamp_column()
265 .and_then(|column| {
266 common_query::logical_plan::build_filter_from_timestamp(&column.name, time_range)
267 })
268 .into_iter()
269 .collect::<Vec<_>>();
270 if self.logical_tables.len() == 1
271 && let Some((&id, _)) = self.logical_tables.first_key_value()
272 {
273 filters.push(col(TABLE_ID).eq(lit(id)));
274 }
275 let source = Arc::new(DefaultTableSource::new(Arc::new(
276 DfTableProviderAdapter::new(self.physical_table.clone()),
277 )));
278 let mut builder = LogicalPlanBuilder::scan_with_filters(
279 DfTableReference::full(
280 info.catalog_name.clone(),
281 info.schema_name.clone(),
282 info.name.clone(),
283 ),
284 source,
285 Some(self.scan_projection.clone()),
286 filters.clone(),
287 )
288 .context(error::BuildDfLogicalPlanSnafu)?;
289 for filter in filters {
290 builder = builder
291 .filter(filter)
292 .context(error::BuildDfLogicalPlanSnafu)?;
293 }
294 if self.logical_tables.len() > 1 {
296 builder = builder
297 .sort(vec![col(TABLE_ID).sort(true, false)])
298 .context(error::BuildDfLogicalPlanSnafu)?;
299 }
300 builder.build().context(error::BuildDfLogicalPlanSnafu)
301 }
302}
303
304#[derive(Debug, Default, PartialEq, Eq)]
306pub struct LogicalTableExportSummary {
307 pub rows: usize,
308 pub skipped_rows: usize,
309 pub files: usize,
310}
311
312impl StatementExecutor {
313 #[allow(clippy::too_many_arguments)]
319 pub async fn export_logical_tables(
320 &self,
321 unit: &LogicalTableExport,
322 directory: &str,
323 connection: &HashMap<String, String>,
324 time_range: Option<&TimestampRange>,
325 limits: LogicalTableExportLimits,
326 cancellation: &CancellationToken,
327 query_ctx: QueryContextRef,
328 ) -> Result<LogicalTableExportSummary> {
329 self.export_logical_tables_managed(
330 unit,
331 directory,
332 connection,
333 time_range,
334 limits,
335 &cancellation.child_token(),
336 query_ctx,
337 ExportWriteBudget::new(1),
338 None,
339 )
340 .await
341 }
342
343 #[allow(clippy::too_many_arguments)]
344 pub(crate) async fn export_logical_tables_managed(
345 &self,
346 unit: &LogicalTableExport,
347 directory: &str,
348 connection: &HashMap<String, String>,
349 time_range: Option<&TimestampRange>,
350 limits: LogicalTableExportLimits,
351 cancellation: &CancellationToken,
352 query_ctx: QueryContextRef,
353 budget: Arc<ExportWriteBudget>,
354 packed: Option<PackedWriterRef>,
355 ) -> Result<LogicalTableExportSummary> {
356 limits.validate()?;
357 let (destination, stream) = tokio::select! {
358 biased;
359 _ = cancellation.cancelled() => return error::LogicalTableExportCancelledSnafu.fail(),
360 result = async {
361 unit.validate_table_routes(self.table_metadata_manager.table_route_manager()).await?;
362 let destination = LogicalExportDestination::new(directory, connection, &self.local_file_access, &self.remote_storage_access, packed).await?;
363 let output = self.query_engine.execute(unit.build_plan(time_range)?, query_ctx)
364 .await.context(error::ExecLogicalPlanSnafu)?;
365 let stream = match output.data {
366 OutputData::Stream(stream) => stream,
367 OutputData::RecordBatches(batches) => batches.as_stream(),
368 _ => return error::UnexpectedSnafu { violated: "expected physical query rows" }.fail(),
369 };
370 Ok((destination, stream))
371 } => result?,
372 };
373 export_stream_managed(unit, stream, destination, limits, cancellation, budget).await
374 }
375}
376
377pub(crate) enum LogicalExportDestination {
379 Object(ObjectStore),
380 Packed(PackedWriterRef),
381}
382
383impl LogicalExportDestination {
384 async fn new(
385 directory: &str,
386 connection: &HashMap<String, String>,
387 local_file_access: &LocalFileAccess,
388 remote_storage_access: &RemoteStorageAccess,
389 packed: Option<PackedWriterRef>,
390 ) -> Result<Self> {
391 if let Some(packed) = packed {
392 return Ok(Self::Packed(packed));
393 }
394 let store = build_backend_for_write(
395 &format!("{}/", directory.trim_end_matches('/')),
396 connection,
397 local_file_access,
398 remote_storage_access,
399 )
400 .await
401 .context(error::BuildBackendSnafu)?;
402 Ok(Self::Object(store))
403 }
404}
405
406#[cfg(test)]
407async fn export_stream(
408 unit: &LogicalTableExport,
409 stream: SendableRecordBatchStream,
410 store: &ObjectStore,
411 limits: LogicalTableExportLimits,
412 cancellation: &CancellationToken,
413) -> Result<LogicalTableExportSummary> {
414 export_stream_managed(
415 unit,
416 stream,
417 LogicalExportDestination::Object(store.clone()),
418 limits,
419 &cancellation.child_token(),
420 ExportWriteBudget::new(1),
421 )
422 .await
423}
424
425async fn export_stream_managed(
426 unit: &LogicalTableExport,
427 stream: SendableRecordBatchStream,
428 destination: LogicalExportDestination,
429 limits: LogicalTableExportLimits,
430 cancellation: &CancellationToken,
431 budget: Arc<ExportWriteBudget>,
432) -> Result<LogicalTableExportSummary> {
433 let mut writers = TableWriters::new(budget.clone());
434 let result = write_tables(
435 unit,
436 stream,
437 &destination,
438 limits,
439 cancellation,
440 &mut writers,
441 &budget,
442 )
443 .await;
444 let (summary, result) = match result {
445 Ok(summary) => (summary, Ok(())),
446 Err(error) => (LogicalTableExportSummary::default(), Err(error)),
447 };
448 writers.drain(result, cancellation).await?;
449 Ok(summary)
450}
451
452fn check_cancelled(cancellation: &CancellationToken) -> Result<()> {
453 ensure!(
454 !cancellation.is_cancelled(),
455 error::LogicalTableExportCancelledSnafu
456 );
457 Ok(())
458}
459
460async fn write_tables(
461 unit: &LogicalTableExport,
462 mut stream: SendableRecordBatchStream,
463 destination: &LogicalExportDestination,
464 limits: LogicalTableExportLimits,
465 cancellation: &CancellationToken,
466 writers: &mut TableWriters,
467 budget: &ExportWriteBudget,
468) -> Result<LogicalTableExportSummary> {
469 let id_index =
470 stream
471 .schema()
472 .column_index_by_name(TABLE_ID)
473 .context(error::UnexpectedSnafu {
474 violated: "physical query omitted __table_id",
475 })?;
476 let mut summary = LogicalTableExportSummary::default();
477 let mut previous = None;
478 let mut written = BTreeSet::new();
479 loop {
480 let batch = tokio::select! {
481 biased;
482 _ = cancellation.cancelled() => return error::LogicalTableExportCancelledSnafu.fail(),
483 batch = stream.next() => batch,
484 };
485 let Some(batch) = batch else {
486 break;
487 };
488 let batch = batch
489 .context(error::BuildRecordBatchSnafu)?
490 .into_df_record_batch();
491 ensure!(
492 batch.get_array_memory_size() <= limits.input_batch_bytes,
493 LogicalTableExportResourceSnafu {
494 reason: "scan batch exceeds input byte budget"
495 }
496 );
497 let ids = batch
498 .column(id_index)
499 .as_any()
500 .downcast_ref::<UInt32Array>()
501 .context(error::UnexpectedSnafu {
502 violated: "__table_id must be UInt32",
503 })?;
504 ensure!(
505 ids.null_count() == 0,
506 error::UnexpectedSnafu {
507 violated: "null __table_id"
508 }
509 );
510 let mut start = 0;
511 while start < batch.num_rows() {
512 check_cancelled(cancellation)?;
513 let id = ids.value(start);
514 ensure!(
515 previous.is_none_or(|last| last <= id),
516 error::UnexpectedSnafu {
517 violated: "physical query is not ordered by __table_id"
518 }
519 );
520 previous = Some(id);
521 let mut end = start + 1;
522 while end < batch.num_rows() && ids.value(end) == id {
523 end += 1;
524 }
525 if writers.table_id().is_some_and(|last| last != id) {
526 writers.close_input();
527 }
528 check_cancelled(cancellation)?;
529 if let Some(file) = unit.logical_tables.get(&id) {
530 if writers.table_id().is_none() {
531 writers
532 .open(id, file, destination, limits, cancellation)
533 .await?;
534 written.insert(id);
535 summary.files += 1;
536 }
537 let projected = batch
538 .project(&file.projection)
539 .context(error::ProjectSchemaSnafu)?;
540 let mut offset = start;
541 while offset < end {
542 let (expanded, consumed) = expand_bounded_slice(
543 projected.clone(),
544 file.schema.clone(),
545 offset,
546 end,
547 limits.conversion_bytes,
548 budget,
549 cancellation,
550 )
551 .await?;
552 check_cancelled(cancellation)?;
553 writers.send(expanded, cancellation).await?;
554 check_cancelled(cancellation)?;
555 offset += consumed;
556 summary.rows += consumed;
557 }
558 } else {
559 summary.skipped_rows += end - start;
560 }
561 start = end;
562 }
563 }
564 writers.close_input();
565 for (&id, file) in &unit.logical_tables {
566 if !written.contains(&id) {
567 check_cancelled(cancellation)?;
568 writers
569 .open(id, file, destination, limits, cancellation)
570 .await?;
571 writers.close_input();
572 summary.files += 1;
573 }
574 }
575 check_cancelled(cancellation)?;
576 Ok(summary)
577}
578
579struct ActiveWriter {
580 path: String,
581 writer: ParquetFileWriter,
582}
583
584impl ActiveWriter {
585 fn open_packed(
586 table: &LogicalTableProjection,
587 id: u32,
588 limits: LogicalTableExportLimits,
589 shared: PackedWriterRef,
590 ) -> Result<Self> {
591 let packed = PackedTableWriter::new(shared, table.name.clone(), id, false);
592 let path = packed.path().to_owned();
593 let writer =
594 ParquetFileWriter::open_packed(table.schema.clone(), Some(limits.writer), packed)
595 .map_err(|e| map_writer_error(e, &path))?;
596 Ok(Self { path, writer })
597 }
598
599 async fn open(
600 table: &LogicalTableProjection,
601 store: &ObjectStore,
602 limits: LogicalTableExportLimits,
603 ) -> Result<Self> {
604 let path = table.output.path.clone();
605 let conditional = store.info().capability().write_with_if_not_exists;
606 if !conditional {
607 ensure!(
608 !store
609 .exists(&path)
610 .await
611 .context(error::ReadObjectSnafu { path: &path })?,
612 InvalidLogicalTableExportSnafu {
613 reason: format!("output already exists: {path}")
614 }
615 );
616 }
617 let writer = ParquetFileWriter::open_with_creation(
618 table.schema.clone(),
619 store.clone(),
620 &path,
621 1,
622 Some(limits.writer),
623 if conditional {
624 ParquetCreationPolicy::IfNotExists
625 } else {
626 ParquetCreationPolicy::Overwrite
627 },
628 )
629 .await
630 .map_err(|error| map_writer_error(error, &path))?;
631 Ok(Self { path, writer })
632 }
633}
634
635async fn expand_bounded_slice(
636 batch: RecordBatch,
637 schema: SchemaRef,
638 start: usize,
639 end: usize,
640 requested: usize,
641 budget: &ExportWriteBudget,
642 cancellation: &CancellationToken,
643) -> Result<(Payload, usize)> {
644 let (conversion, retained) = ExportWriteBudget::conversion_budget(
645 batch.get_array_memory_size(),
646 batch.num_columns(),
647 requested,
648 )?;
649 let fields = schema
651 .fields()
652 .iter()
653 .zip(batch.columns())
654 .map(|(field, array)| {
655 if let DataType::Dictionary(_, value) = array.data_type()
656 && value.as_ref() == field.data_type()
657 && matches!(value.as_ref(), DataType::Utf8 | DataType::LargeUtf8)
658 {
659 Arc::new(
660 field
661 .as_ref()
662 .clone()
663 .with_data_type(array.data_type().clone()),
664 )
665 } else {
666 field.clone()
667 }
668 })
669 .collect::<Vec<_>>();
670 let schema = Arc::new(arrow::datatypes::Schema::new_with_metadata(
671 fields,
672 schema.metadata().clone(),
673 ));
674 if start < end
677 && batch
678 .columns()
679 .iter()
680 .zip(schema.fields())
681 .all(|(array, field)| array.data_type() == field.data_type())
682 && let Some(estimated) = estimate_batch_bytes_upper_bound(&batch, end - start, &[])?
683 && estimated <= conversion
684 {
685 let reservation = retained.saturating_add(estimated.saturating_mul(4));
686 let permit = budget.reserve(reservation, cancellation).await?;
687 return convert_slice_payload(batch, schema, start, end - start, reservation, permit);
688 }
689 let input = batch.clone();
690 let (len, estimated) = common_runtime::spawn_blocking_global(move || {
691 rows_within_budget(&input, start, end, conversion, &[])
692 })
693 .await
694 .context(error::JoinTaskSnafu)??;
695 let reservation = retained.saturating_add(estimated.saturating_mul(4));
696 let permit = budget.reserve(reservation, cancellation).await?;
697 common_runtime::spawn_blocking_global(move || {
698 convert_slice_payload(batch, schema, start, len, reservation, permit)
699 })
700 .await
701 .context(error::JoinTaskSnafu)?
702}
703
704fn convert_slice_payload(
705 batch: RecordBatch,
706 schema: SchemaRef,
707 start: usize,
708 len: usize,
709 reservation: usize,
710 permit: OwnedSemaphorePermit,
711) -> Result<(Payload, usize)> {
712 let expanded = expand_export_batch(&batch.slice(start, len), schema)?;
713 ensure!(
714 expanded.get_array_memory_size() <= reservation,
715 LogicalTableExportResourceSnafu {
716 reason: "converted backing buffers exceed reservation"
717 }
718 );
719 Ok((
720 Payload {
721 batch: expanded,
722 permit,
723 },
724 len,
725 ))
726}
727
728pub(crate) fn expand_export_batch(batch: &RecordBatch, schema: SchemaRef) -> Result<RecordBatch> {
731 let arrays = batch
732 .columns()
733 .iter()
734 .zip(schema.fields())
735 .map(|(array, field)| expand_export_array(array, field.data_type()))
736 .collect::<Result<Vec<_>>>()?;
737 RecordBatch::try_new(schema, arrays).context(error::ComputeArrowSnafu)
738}
739
740fn expand_export_array(array: &ArrayRef, target: &DataType) -> Result<ArrayRef> {
741 if array.data_type() == target {
742 return Ok(array.clone());
743 }
744 match (array.data_type(), target) {
745 (DataType::Dictionary(_, _), _) => {
746 downcast_dictionary_array! {
747 array => {
748 let selected = take(array.values().as_ref(), array.keys(), None)
750 .context(error::ComputeArrowSnafu)?;
751 expand_export_array(&selected, target)
752 },
753 _ => error::UnexpectedSnafu { violated: "invalid dictionary array" }.fail(),
754 }
755 }
756 (DataType::List(_), DataType::List(field)) => {
757 let list = array.as_list::<i32>();
758 let offsets = list.value_offsets();
759 let start = offsets[0];
760 let end = offsets[list.len()];
761 let values = list.values().slice(start as usize, (end - start) as usize);
762 let values = expand_export_array(&values, field.data_type())?;
763 let offsets = OffsetBuffer::new(
764 offsets
765 .iter()
766 .map(|offset| offset - start)
767 .collect::<Vec<_>>()
768 .into(),
769 );
770 Ok(Arc::new(
771 ListArray::try_new(field.clone(), offsets, values, list.nulls().cloned())
772 .context(error::ComputeArrowSnafu)?,
773 ))
774 }
775 (DataType::Struct(_), DataType::Struct(fields)) => {
776 let array = array.as_struct();
777 let columns = array
778 .columns()
779 .iter()
780 .zip(fields)
781 .map(|(array, field)| expand_export_array(array, field.data_type()))
782 .collect::<Result<Vec<_>>>()?;
783 Ok(Arc::new(
784 StructArray::try_new(fields.clone(), columns, array.nulls().cloned())
785 .context(error::ComputeArrowSnafu)?,
786 ))
787 }
788 _ => cast(array, target).context(error::ComputeArrowSnafu),
789 }
790}
791
792pub(crate) fn map_writer_error(
793 source: common_datasource::error::Error,
794 path: &str,
795) -> error::Error {
796 match source {
797 common_datasource::error::Error::ParquetWriteCancelled {} => {
798 error::LogicalTableExportCancelledSnafu.build()
799 }
800 common_datasource::error::Error::InvalidParquetWriterLimits {} => {
801 InvalidLogicalTableExportSnafu {
802 reason: "Parquet writer limits must be positive",
803 }
804 .build()
805 }
806 common_datasource::error::Error::ParquetWriterResource { reason } => {
807 LogicalTableExportResourceSnafu { reason }.build()
808 }
809 common_datasource::error::Error::WriteObject { error, .. }
810 if error.kind() == object_store::ErrorKind::ConditionNotMatch =>
811 {
812 let reason = format!("output already exists: {path}");
813 InvalidLogicalTableExportSnafu { reason }.build()
814 }
815 source => error::WriteStreamToFileSnafu { path }.into_error(source),
816 }
817}
818
819fn estimate_value_size(array: &dyn Array, row: usize) -> Result<usize> {
822 if array.is_null(row) && !matches!(array.data_type(), DataType::Struct(_) | DataType::List(_)) {
823 return Ok(32);
824 }
825 let bytes = match array.data_type() {
826 DataType::Boolean => 1,
827 DataType::Null => 0,
828 DataType::Utf8 => array.as_string::<i32>().value(row).len(),
829 DataType::LargeUtf8 => array.as_string::<i64>().value(row).len(),
830 DataType::Utf8View => array.as_string_view().value(row).len(),
831 DataType::Binary => array.as_binary::<i32>().value(row).len(),
832 DataType::LargeBinary => array.as_binary::<i64>().value(row).len(),
833 DataType::BinaryView => array.as_binary_view().value(row).len(),
834 DataType::Struct(_) => {
835 array
836 .as_struct()
837 .columns()
838 .iter()
839 .try_fold(0usize, |sum, child| {
840 Ok::<_, error::Error>(
841 sum.saturating_add(estimate_value_size(child.as_ref(), row)?),
842 )
843 })?
844 }
845 DataType::List(_) => {
846 let list = array.as_list::<i32>();
847 let offsets = list.value_offsets();
848 (offsets[row] as usize..offsets[row + 1] as usize).try_fold(0usize, |sum, index| {
849 Ok::<_, error::Error>(
850 sum.saturating_add(estimate_value_size(list.values().as_ref(), index)?),
851 )
852 })?
853 }
854 DataType::Dictionary(_, _) => {
855 downcast_dictionary_array! {
856 array => {
857 match array.key(row) {
858 Some(index) => estimate_value_size(array.values().as_ref(), index)?,
859 None => 0,
860 }
861 },
862 _ => return error::UnexpectedSnafu { violated: "invalid dictionary array" }.fail(),
863 }
864 }
865 other => other
866 .primitive_width()
867 .with_context(|| InvalidLogicalTableExportSnafu {
868 reason: format!("unsupported Metric Parquet type: {other}"),
869 })?,
870 };
871 Ok(bytes.saturating_add(16))
872}
873
874fn estimate_batch_bytes_upper_bound(
877 batch: &RecordBatch,
878 rows: usize,
879 json_columns: &[usize],
880) -> Result<Option<usize>> {
881 let mut dictionary_values = 1024usize;
882 let mut max_row_bytes = 0usize;
883 for (index, array) in batch.columns().iter().enumerate() {
884 let size = if let Some(width) = array.data_type().primitive_width() {
885 (width + 16).max(32)
886 } else if let Some(dictionary) = array.as_any_dictionary_opt()
887 && dictionary.values().len() < rows
888 && dictionary.values().len() <= dictionary_values
889 && matches!(
890 dictionary.values().data_type(),
891 DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View
892 )
893 {
894 let values = dictionary.values();
895 dictionary_values -= values.len();
896 let max = (0..values.len()).try_fold(0usize, |max, row| {
897 Ok::<_, error::Error>(max.max(estimate_value_size(values.as_ref(), row)?))
898 })?;
899 max.saturating_add(16).max(32)
900 } else {
901 return Ok(None);
902 };
903 let expansion = if json_columns.contains(&index) { 8 } else { 1 };
904 max_row_bytes = max_row_bytes.saturating_add(size.saturating_mul(expansion));
905 }
906 Ok(max_row_bytes.checked_mul(rows))
907}
908
909pub(crate) fn rows_within_budget(
910 batch: &RecordBatch,
911 start: usize,
912 end: usize,
913 budget: usize,
914 json_columns: &[usize],
915) -> Result<(usize, usize)> {
916 if start < end
917 && let Some(bytes) = estimate_batch_bytes_upper_bound(batch, end - start, json_columns)?
918 && bytes <= budget
919 {
920 return Ok((end - start, bytes));
921 }
922 let mut bytes = 0usize;
923 let mut row = start;
924 while row < end {
925 let row_bytes =
926 batch
927 .columns()
928 .iter()
929 .enumerate()
930 .try_fold(0usize, |sum, (index, array)| {
931 let expansion = if json_columns.contains(&index) && !array.is_null(row) {
933 8
934 } else {
935 1
936 };
937 let size = estimate_value_size(array.as_ref(), row)?;
938 Ok::<_, error::Error>(sum.saturating_add(size.saturating_mul(expansion)))
939 })?;
940 if row_bytes > budget.saturating_sub(bytes) {
941 break;
942 }
943 bytes += row_bytes;
944 row += 1;
945 }
946 ensure!(
947 row > start,
948 LogicalTableExportResourceSnafu {
949 reason: "one expanded logical row exceeds conversion byte budget"
950 }
951 );
952 Ok((row - start, bytes))
953}
954
955#[cfg(test)]
956mod tests;