Repository navigation
Expand file tree
/
Copy pathtable.rs
More file actions
2101 lines (1873 loc) · 75.5 KB
/
Copy pathtable.rs
File metadata and controls
2101 lines (1873 loc) · 75.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
use crate::execution::SessionState;
use async_trait::async_trait;
use datafusion_catalog_listing::{ListingOptions, ListingTableConfig};
use datafusion_common::{config_datafusion_err, internal_datafusion_err};
use datafusion_session::Session;
use futures::StreamExt;
use futures::future::BoxFuture;
use std::collections::HashMap;
/// Extension trait for [`ListingTableConfig`] that supports inferring schemas
///
/// This trait exists because the following inference methods only
/// work for [`SessionState`] implementations of [`Session`].
/// See [`ListingTableConfig`] for the remaining inference methods.
#[async_trait]
pub trait ListingTableConfigExt {
/// Infer `ListingOptions` based on `table_path` and file suffix.
///
/// The format is inferred based on the first `table_path`.
async fn infer_options(
self,
state: &dyn Session,
) -> datafusion_common::Result<ListingTableConfig>;
/// Convenience method to call both [`Self::infer_options`] and [`ListingTableConfig::infer_schema`]
async fn infer(
self,
state: &dyn Session,
) -> datafusion_common::Result<ListingTableConfig>;
}
#[async_trait]
impl ListingTableConfigExt for ListingTableConfig {
// Hand-written `#[async_trait]` expansion to reduce compile time. See
// <https://github.com/apache/datafusion/issues/13814#issuecomment-5292709677>
fn infer_options<'life0, 'async_trait>(
self,
state: &'life0 dyn Session,
) -> BoxFuture<'async_trait, datafusion_common::Result<ListingTableConfig>>
where
'life0: 'async_trait,
Self: 'async_trait,
{
infer_options_boxed(self, state)
}
// Hand-written `#[async_trait]` expansion to reduce compile time. See
// <https://github.com/apache/datafusion/issues/13814#issuecomment-5292709677>
fn infer<'life0, 'async_trait>(
self,
state: &'life0 dyn Session,
) -> BoxFuture<'async_trait, datafusion_common::Result<Self>>
where
'life0: 'async_trait,
Self: 'async_trait,
{
infer_boxed(self, state)
}
}
/// Body of [`ListingTableConfigExt::infer`].
fn infer_boxed(
config: ListingTableConfig,
state: &dyn Session,
) -> BoxFuture<'_, datafusion_common::Result<ListingTableConfig>> {
Box::pin(async move { config.infer_options(state).await?.infer_schema(state).await })
}
/// Body of [`ListingTableConfigExt::infer_options`].
fn infer_options_boxed(
config: ListingTableConfig,
state: &dyn Session,
) -> BoxFuture<'_, datafusion_common::Result<ListingTableConfig>> {
Box::pin(async move {
let store = if let Some(url) = config.table_paths.first() {
state.runtime_env().object_store(url)?
} else {
return Ok(config);
};
let file = config
.table_paths
.first()
.unwrap()
.list_all_files(state, store.as_ref(), "")
.await?
.next()
.await
.ok_or_else(|| internal_datafusion_err!("No files for table"))??;
let (file_extension, maybe_compression_type) =
ListingTableConfig::infer_file_extension_and_compression_type(
file.location.as_ref(),
)?;
let mut format_options = HashMap::new();
if let Some(ref compression_type) = maybe_compression_type {
format_options
.insert("format.compression".to_string(), compression_type.clone());
}
let state = state.as_any().downcast_ref::<SessionState>().unwrap();
let file_format = state
.get_file_format_factory(&file_extension)
.ok_or(config_datafusion_err!(
"No file_format found with extension {file_extension}"
))?
.create(state, &format_options)?;
let listing_file_extension =
if let Some(compression_type) = maybe_compression_type {
format!("{file_extension}.{compression_type}")
} else {
file_extension
};
let listing_options =
ListingOptions::new(file_format).with_file_extension(listing_file_extension);
Ok(config.with_listing_options(listing_options))
})
}
#[cfg(test)]
mod tests {
#[cfg(feature = "parquet")]
use crate::datasource::file_format::parquet::ParquetFormat;
use crate::datasource::listing::table::ListingTableConfigExt;
use crate::execution::options::JsonReadOptions;
use crate::prelude::*;
use crate::{
datasource::{
DefaultTableSource, MemTable, file_format::csv::CsvFormat,
file_format::json::JsonFormat, provider_as_source,
},
execution::options::ArrowReadOptions,
test::{
columns, object_store::ensure_head_concurrency,
object_store::make_test_store_and_state, object_store::register_test_store,
},
};
use arrow::{compute::SortOptions, record_batch::RecordBatch};
use arrow_schema::{DataType, Field, Schema, SchemaRef, TimeUnit};
use datafusion_catalog::{ScanArgs, TableProvider};
use datafusion_catalog_listing::{
ListingOptions, ListingTable, ListingTableConfig, SchemaSource,
};
use datafusion_common::{
DataFusionError, Result, ScalarValue, assert_contains,
stats::Precision,
test_util::{batches_to_string, datafusion_test_data},
};
use datafusion_datasource::ListingTableUrl;
use datafusion_datasource::file_compression_type::FileCompressionType;
use datafusion_datasource::file_format::FileFormat;
use datafusion_expr::dml::InsertOp;
use datafusion_expr::{
BinaryExpr, LogicalPlanBuilder, Operator, Partitioning as LogicalPartitioning,
RangePartitioning as LogicalRangePartitioning,
};
use datafusion_physical_expr::PhysicalSortExpr;
use datafusion_physical_expr::expressions::{Column, binary};
use datafusion_physical_expr_common::sort_expr::LexOrdering;
use datafusion_physical_plan::empty::EmptyExec;
use datafusion_physical_plan::statistics::{StatisticsArgs, StatisticsContext};
use datafusion_physical_plan::{
ExecutionPlanProperties, Partitioning, RangePartitioning, SplitPoint, collect,
};
use std::collections::HashMap;
use std::io::Write;
use std::sync::Arc;
use tempfile::TempDir;
use url::Url;
/// Creates a test schema with standard field types used in tests
fn create_test_schema() -> SchemaRef {
Arc::new(Schema::new(vec![
Field::new("c1", DataType::Float32, true),
Field::new("c2", DataType::Float64, true),
Field::new("c3", DataType::Boolean, true),
Field::new("c4", DataType::Utf8, true),
]))
}
/// Helper function to generate test file paths with given prefix, count, and optional start index
fn generate_test_files(prefix: &str, count: usize) -> Vec<String> {
generate_test_files_with_start(prefix, count, 0)
}
/// Helper function to generate test file paths with given prefix, count, and start index
fn generate_test_files_with_start(
prefix: &str,
count: usize,
start_index: usize,
) -> Vec<String> {
(start_index..start_index + count)
.map(|i| format!("{prefix}/file{i}"))
.collect()
}
fn listing_table_with_files(
ctx: &SessionContext,
files: &[&str],
table_path: &str,
options: ListingOptions,
schema: Schema,
) -> Result<ListingTable> {
register_test_store(ctx, &files.iter().map(|f| (*f, 10)).collect::<Vec<_>>());
let config = ListingTableConfig::new(ListingTableUrl::parse(table_path)?)
.with_listing_options(options)
.with_schema(Arc::new(schema));
ListingTable::try_new(config)
}
#[tokio::test]
async fn test_schema_source_tracking_comprehensive() -> Result<()> {
let ctx = SessionContext::new();
let testdata = datafusion_test_data();
let filename = format!("{testdata}/aggregate_simple.csv");
let table_path = ListingTableUrl::parse(filename)?;
// Test default schema source
let format = CsvFormat::default();
let options = ListingOptions::new(Arc::new(format));
let config =
ListingTableConfig::new(table_path.clone()).with_listing_options(options);
assert_eq!(config.schema_source(), SchemaSource::Unset);
// Test schema source after setting a schema explicitly
let provided_schema = create_test_schema();
let config_with_schema = config.clone().with_schema(provided_schema.clone());
assert_eq!(config_with_schema.schema_source(), SchemaSource::Specified);
// Test schema source after inferring schema
assert_eq!(config.schema_source(), SchemaSource::Unset);
let config_with_inferred = config.infer_schema(&ctx.state()).await?;
assert_eq!(config_with_inferred.schema_source(), SchemaSource::Inferred);
// Test schema preservation through operations
let config_with_schema_and_options = config_with_schema.clone();
assert_eq!(
config_with_schema_and_options.schema_source(),
SchemaSource::Specified
);
// Make sure inferred schema doesn't override specified schema
let config_with_schema_and_infer = config_with_schema_and_options
.clone()
.infer(&ctx.state())
.await?;
assert_eq!(
config_with_schema_and_infer.schema_source(),
SchemaSource::Specified
);
// Verify sources in actual ListingTable objects
let table_specified = ListingTable::try_new(config_with_schema_and_options)?;
assert_eq!(table_specified.schema_source(), SchemaSource::Specified);
let table_inferred = ListingTable::try_new(config_with_inferred)?;
assert_eq!(table_inferred.schema_source(), SchemaSource::Inferred);
Ok(())
}
#[tokio::test]
async fn read_single_file() -> Result<()> {
let ctx = SessionContext::new_with_config(
SessionConfig::new().with_collect_statistics(true),
);
let table = load_table(&ctx, "alltypes_plain.parquet").await?;
let projection = None;
let exec = table
.scan(&ctx.state(), projection, &[], None)
.await
.expect("Scan table");
assert_eq!(exec.children().len(), 0);
assert_eq!(exec.output_partitioning().partition_count(), 1);
// test metadata
assert_eq!(
StatisticsContext::new()
.compute(exec.as_ref(), &StatisticsArgs::new())?
.num_rows,
Precision::Exact(8)
);
assert_eq!(
StatisticsContext::new()
.compute(exec.as_ref(), &StatisticsArgs::new())?
.total_byte_size,
Precision::Absent,
);
Ok(())
}
#[cfg(feature = "parquet")]
#[tokio::test]
async fn scan_with_args_skip_skips_correct_rows() -> Result<()> {
for target_partition in [1_usize, 8, 16] {
let ctx = SessionContext::new_with_config(
SessionConfig::new().with_target_partitions(target_partition),
);
let table = load_table(&ctx, "alltypes_plain.parquet").await?;
// Full scan (no skip) establishes the expected row order.
let full_exec = table
.scan_with_args(&ctx.state(), ScanArgs::default())
.await?
.into_inner();
let full_batches = collect(full_exec, ctx.task_ctx()).await?;
let full =
arrow::compute::concat_batches(&full_batches[0].schema(), &full_batches)?;
assert_eq!(full.num_rows(), 8);
let expected = full.slice(2, 3);
// `LIMIT 3 OFFSET 2` should return exactly rows [2, 5), in order —
// not just the first 3 rows.
let skip_exec = table
.scan_with_args(
&ctx.state(),
ScanArgs::default().with_limit(Some(3)).with_skip(Some(2)),
)
.await?
.into_inner();
let skip_batches = collect(skip_exec, ctx.task_ctx()).await?;
let actual =
arrow::compute::concat_batches(&skip_batches[0].schema(), &skip_batches)?;
assert_eq!(actual.num_rows(), 3);
assert_eq!(batches_to_string(&[expected]), batches_to_string(&[actual]));
}
Ok(())
}
#[cfg(feature = "parquet")]
#[tokio::test]
async fn test_try_create_output_ordering() {
let testdata = crate::test_util::parquet_test_data();
let filename = format!("{}/{}", testdata, "alltypes_plain.parquet");
let table_path = ListingTableUrl::parse(filename).unwrap();
let ctx = SessionContext::new();
let state = ctx.state();
let options = ListingOptions::new(Arc::new(ParquetFormat::default()));
let schema = options.infer_schema(&state, &table_path).await.unwrap();
use crate::datasource::file_format::parquet::ParquetFormat;
use datafusion_physical_plan::expressions::col as physical_col;
use datafusion_physical_plan::expressions::lit as physical_lit;
use std::ops::Add;
// (file_sort_order, expected_result)
let cases = vec![
(
vec![],
Ok::<Vec<LexOrdering>, DataFusionError>(Vec::<LexOrdering>::new()),
),
// sort expr, but non column
(
vec![vec![col("int_col").add(lit(1)).sort(true, true)]],
Ok(vec![
[PhysicalSortExpr {
expr: binary(
physical_col("int_col", &schema).unwrap(),
Operator::Plus,
physical_lit(1),
&schema,
)
.unwrap(),
options: SortOptions {
descending: false,
nulls_first: true,
},
}]
.into(),
]),
),
// ok with one column
(
vec![vec![col("string_col").sort(true, false)]],
Ok(vec![
[PhysicalSortExpr {
expr: physical_col("string_col", &schema).unwrap(),
options: SortOptions {
descending: false,
nulls_first: false,
},
}]
.into(),
]),
),
// ok with two columns, different options
(
vec![vec![
col("string_col").sort(true, false),
col("int_col").sort(false, true),
]],
Ok(vec![
[
PhysicalSortExpr::new_default(
physical_col("string_col", &schema).unwrap(),
)
.asc()
.nulls_last(),
PhysicalSortExpr::new_default(
physical_col("int_col", &schema).unwrap(),
)
.desc()
.nulls_first(),
]
.into(),
]),
),
];
for (file_sort_order, expected_result) in cases {
let options = options.clone().with_file_sort_order(file_sort_order);
let config = ListingTableConfig::new(table_path.clone())
.with_listing_options(options)
.with_schema(schema.clone());
let table =
ListingTable::try_new(config.clone()).expect("Creating the table");
let ordering_result =
table.try_create_output_ordering(state.execution_props(), &[]);
match (expected_result, ordering_result) {
(Ok(expected), Ok(result)) => {
assert_eq!(expected, result);
}
(Err(expected), Err(result)) => {
// can't compare the DataFusionError directly
let result = result.to_string();
let expected = expected.to_string();
assert_contains!(result.to_string(), expected);
}
(expected_result, ordering_result) => {
panic!(
"expected: {expected_result:#?}\n\nactual:{ordering_result:#?}"
);
}
}
}
}
#[tokio::test]
async fn read_empty_table() -> Result<()> {
let ctx = SessionContext::new_with_config(
SessionConfig::new().with_target_partitions(4),
);
let path = String::from("table/p1=v1/file.json");
register_test_store(&ctx, &[(&path, 100)]);
let format = JsonFormat::default();
let ext = format.get_ext();
let opt = ListingOptions::new(Arc::new(format))
.with_file_extension(ext)
.with_table_partition_cols(vec![(String::from("p1"), DataType::Utf8)]);
let table_path = ListingTableUrl::parse("test:///table/")?;
let file_schema =
Arc::new(Schema::new(vec![Field::new("a", DataType::Boolean, false)]));
let config = ListingTableConfig::new(table_path)
.with_listing_options(opt)
.with_schema(file_schema);
let table = ListingTable::try_new(config)?;
assert_eq!(
columns(&table.schema()),
vec!["a".to_owned(), "p1".to_owned()]
);
// this will filter out the only file in the store
let filter = Expr::not_eq(col("p1"), lit("v1"));
let scan = table
.scan(&ctx.state(), None, &[filter], None)
.await
.expect("Empty execution plan");
assert!(scan.is::<EmptyExec>());
assert_eq!(
columns(&scan.schema()),
vec!["a".to_owned(), "p1".to_owned()]
);
Ok(())
}
async fn load_table(
ctx: &SessionContext,
name: &str,
) -> Result<Arc<dyn TableProvider>> {
let testdata = crate::test_util::parquet_test_data();
let filename = format!("{testdata}/{name}");
let table_path = ListingTableUrl::parse(filename)?;
let config = ListingTableConfig::new(table_path)
.infer(&ctx.state())
.await?;
let table = ListingTable::try_new(config)?;
Ok(Arc::new(table))
}
/// Check that the files listed by the table match the specified `output_partitioning`
/// when the object store contains `files`.
async fn assert_list_files_for_scan_grouping(
files: &[&str],
table_prefix: &str,
target_partitions: usize,
output_partitioning: usize,
file_ext: Option<&str>,
) -> Result<()> {
let ctx = SessionContext::new_with_config(
SessionConfig::new().with_target_partitions(target_partitions),
);
register_test_store(&ctx, &files.iter().map(|f| (*f, 10)).collect::<Vec<_>>());
let opt = ListingOptions::new(Arc::new(JsonFormat::default()))
.with_file_extension_opt(file_ext);
let schema = Schema::new(vec![Field::new("a", DataType::Boolean, false)]);
let table_path = ListingTableUrl::parse(table_prefix)?;
let config = ListingTableConfig::new(table_path)
.with_listing_options(opt)
.with_schema(Arc::new(schema));
let table = ListingTable::try_new(config)?;
let result = table.list_files_for_scan(&ctx.state(), &[], None).await?;
assert_eq!(result.file_groups.len(), output_partitioning);
Ok(())
}
/// Check that the files listed by the table match the specified `output_partitioning`
/// when the object store contains `files`.
async fn assert_list_files_for_multi_paths(
files: &[&str],
table_prefix: &[&str],
target_partitions: usize,
output_partitioning: usize,
file_ext: Option<&str>,
) -> Result<()> {
let ctx = SessionContext::new_with_config(
SessionConfig::new().with_target_partitions(target_partitions),
);
register_test_store(&ctx, &files.iter().map(|f| (*f, 10)).collect::<Vec<_>>());
let opt = ListingOptions::new(Arc::new(JsonFormat::default()))
.with_file_extension_opt(file_ext);
let schema = Schema::new(vec![Field::new("a", DataType::Boolean, false)]);
let table_paths = table_prefix
.iter()
.map(|t| ListingTableUrl::parse(t).unwrap())
.collect();
let config = ListingTableConfig::new_with_multi_paths(table_paths)
.with_listing_options(opt)
.with_schema(Arc::new(schema));
let table = ListingTable::try_new(config)?;
let result = table.list_files_for_scan(&ctx.state(), &[], None).await?;
assert_eq!(result.file_groups.len(), output_partitioning);
Ok(())
}
/// Check that the files listed by the table match the specified `output_partitioning`
/// when the object store contains `files`, and validate that file metadata is fetched
/// concurrently
async fn assert_list_files_for_exact_paths(
files: &[&str],
target_partitions: usize,
output_partitioning: usize,
file_ext: Option<&str>,
) -> Result<()> {
let ctx = SessionContext::new_with_config(
SessionConfig::new().with_target_partitions(target_partitions),
);
let (store, _) = make_test_store_and_state(
&files.iter().map(|f| (*f, 10)).collect::<Vec<_>>(),
);
let meta_fetch_concurrency = ctx
.state()
.config_options()
.execution
.meta_fetch_concurrency
.get();
let expected_concurrency = files.len().min(meta_fetch_concurrency);
let head_concurrency_store = ensure_head_concurrency(store, expected_concurrency);
let url = Url::parse("test://").unwrap();
ctx.register_object_store(&url, head_concurrency_store.clone());
let format = JsonFormat::default();
let opt = ListingOptions::new(Arc::new(format)).with_file_extension_opt(file_ext);
let schema = Schema::new(vec![Field::new("a", DataType::Boolean, false)]);
let table_paths = files
.iter()
.map(|t| ListingTableUrl::parse(format!("test:///{t}")).unwrap())
.collect();
let config = ListingTableConfig::new_with_multi_paths(table_paths)
.with_listing_options(opt)
.with_schema(Arc::new(schema));
let table = ListingTable::try_new(config)?;
let result = table.list_files_for_scan(&ctx.state(), &[], None).await?;
assert_eq!(result.file_groups.len(), output_partitioning);
Ok(())
}
#[tokio::test]
async fn test_insert_into_sql_csv_defaults() -> Result<()> {
helper_test_insert_into_sql("csv", FileCompressionType::UNCOMPRESSED, "", None)
.await?;
Ok(())
}
#[tokio::test]
async fn test_insert_into_sql_csv_defaults_header_row() -> Result<()> {
helper_test_insert_into_sql(
"csv",
FileCompressionType::UNCOMPRESSED,
"",
Some(HashMap::from([("has_header".into(), "true".into())])),
)
.await?;
Ok(())
}
#[tokio::test]
async fn test_insert_into_sql_json_defaults() -> Result<()> {
helper_test_insert_into_sql("json", FileCompressionType::UNCOMPRESSED, "", None)
.await?;
Ok(())
}
#[tokio::test]
async fn test_insert_into_sql_parquet_defaults() -> Result<()> {
helper_test_insert_into_sql(
"parquet",
FileCompressionType::UNCOMPRESSED,
"",
None,
)
.await?;
Ok(())
}
#[tokio::test]
async fn test_insert_into_sql_parquet_session_overrides() -> Result<()> {
let mut config_map: HashMap<String, String> = HashMap::new();
config_map.insert(
"datafusion.execution.parquet.compression".into(),
"zstd(5)".into(),
);
config_map.insert(
"datafusion.execution.parquet.dictionary_enabled".into(),
"false".into(),
);
config_map.insert(
"datafusion.execution.parquet.dictionary_page_size_limit".into(),
"100".into(),
);
config_map.insert(
"datafusion.execution.parquet.statistics_enabled".into(),
"none".into(),
);
config_map.insert(
"datafusion.execution.parquet.max_statistics_size".into(),
"10".into(),
);
config_map.insert(
"datafusion.execution.parquet.max_row_group_size".into(),
"5".into(),
);
config_map.insert(
"datafusion.execution.parquet.created_by".into(),
"datafusion test".into(),
);
config_map.insert(
"datafusion.execution.parquet.column_index_truncate_length".into(),
"50".into(),
);
config_map.insert(
"datafusion.execution.parquet.data_page_row_count_limit".into(),
"50".into(),
);
config_map.insert(
"datafusion.execution.parquet.bloom_filter_on_write".into(),
"true".into(),
);
config_map.insert(
"datafusion.execution.parquet.bloom_filter_fpp".into(),
"0.01".into(),
);
config_map.insert(
"datafusion.execution.parquet.bloom_filter_ndv".into(),
"1000".into(),
);
config_map.insert(
"datafusion.execution.parquet.writer_version".into(),
"2.0".into(),
);
config_map.insert(
"datafusion.execution.parquet.write_batch_size".into(),
"5".into(),
);
helper_test_insert_into_sql(
"parquet",
FileCompressionType::UNCOMPRESSED,
"",
Some(config_map),
)
.await?;
Ok(())
}
#[tokio::test]
async fn test_insert_into_append_new_parquet_files_session_overrides() -> Result<()> {
let mut config_map: HashMap<String, String> = HashMap::new();
config_map.insert(
"datafusion.execution.soft_max_rows_per_output_file".into(),
"10".into(),
);
config_map.insert(
"datafusion.execution.soft_max_bytes_per_output_file".into(),
"10".into(),
);
config_map.insert(
"datafusion.execution.parquet.compression".into(),
"zstd(5)".into(),
);
config_map.insert(
"datafusion.execution.parquet.dictionary_enabled".into(),
"false".into(),
);
config_map.insert(
"datafusion.execution.parquet.dictionary_page_size_limit".into(),
"100".into(),
);
config_map.insert(
"datafusion.execution.parquet.statistics_enabled".into(),
"none".into(),
);
config_map.insert(
"datafusion.execution.parquet.max_statistics_size".into(),
"10".into(),
);
config_map.insert(
"datafusion.execution.parquet.max_row_group_size".into(),
"5".into(),
);
config_map.insert(
"datafusion.execution.parquet.created_by".into(),
"datafusion test".into(),
);
config_map.insert(
"datafusion.execution.parquet.column_index_truncate_length".into(),
"50".into(),
);
config_map.insert(
"datafusion.execution.parquet.data_page_row_count_limit".into(),
"50".into(),
);
config_map.insert(
"datafusion.execution.parquet.encoding".into(),
"delta_binary_packed".into(),
);
config_map.insert(
"datafusion.execution.parquet.bloom_filter_on_write".into(),
"true".into(),
);
config_map.insert(
"datafusion.execution.parquet.bloom_filter_fpp".into(),
"0.01".into(),
);
config_map.insert(
"datafusion.execution.parquet.bloom_filter_ndv".into(),
"1000".into(),
);
config_map.insert(
"datafusion.execution.parquet.writer_version".into(),
"2.0".into(),
);
config_map.insert(
"datafusion.execution.parquet.write_batch_size".into(),
"5".into(),
);
config_map.insert("datafusion.execution.batch_size".into(), "10".into());
helper_test_append_new_files_to_table(
ParquetFormat::default().get_ext(),
FileCompressionType::UNCOMPRESSED,
Some(config_map),
2,
)
.await?;
Ok(())
}
#[tokio::test]
async fn test_insert_into_append_new_parquet_files_invalid_session_fails()
-> Result<()> {
let mut config_map: HashMap<String, String> = HashMap::new();
config_map.insert(
"datafusion.execution.parquet.compression".into(),
"zstd".into(),
);
let e = helper_test_append_new_files_to_table(
ParquetFormat::default().get_ext(),
FileCompressionType::UNCOMPRESSED,
Some(config_map),
2,
)
.await
.expect_err("Example should fail!");
// The value is rejected when the option is set, before any file is written
assert_eq!(
e.strip_backtrace(),
"Error setting config datafusion.execution.parquet.compression\ncaused by\nInvalid or Unsupported Configuration: zstd compression requires specifying a level such as zstd(4)"
);
Ok(())
}
async fn helper_test_append_new_files_to_table(
file_type_ext: String,
file_compression_type: FileCompressionType,
session_config_map: Option<HashMap<String, String>>,
expected_n_files_per_insert: usize,
) -> Result<()> {
// Create the initial context, schema, and batch.
let session_ctx = match session_config_map {
Some(cfg) => {
let config = SessionConfig::from_string_hash_map(&cfg)?;
SessionContext::new_with_config(config)
}
None => SessionContext::new(),
};
// Create a new schema with one field called "a" of type Int32
let schema = Arc::new(Schema::new(vec![Field::new(
"column1",
DataType::Int32,
false,
)]));
let filter_predicate = Expr::BinaryExpr(BinaryExpr::new(
Box::new(Expr::Column("column1".into())),
Operator::GtEq,
Box::new(Expr::Literal(ScalarValue::Int32(Some(0)), None)),
));
// Create a new batch of data to insert into the table
let batch = RecordBatch::try_new(
schema.clone(),
vec![Arc::new(arrow::array::Int32Array::from(vec![
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
]))],
)?;
// Register appropriate table depending on file_type we want to test
let tmp_dir = TempDir::new()?;
match file_type_ext.as_str() {
"csv" => {
session_ctx
.register_csv(
"t",
tmp_dir.path().to_str().unwrap(),
CsvReadOptions::new()
.schema(schema.as_ref())
.file_compression_type(file_compression_type),
)
.await?;
}
"json" => {
session_ctx
.register_json(
"t",
tmp_dir.path().to_str().unwrap(),
JsonReadOptions::default()
.schema(schema.as_ref())
.file_compression_type(file_compression_type),
)
.await?;
}
#[cfg(feature = "parquet")]
"parquet" => {
session_ctx
.register_parquet(
"t",
tmp_dir.path().to_str().unwrap(),
ParquetReadOptions::default().schema(schema.as_ref()),
)
.await?;
}
#[cfg(feature = "avro")]
"avro" => {
session_ctx
.register_avro(
"t",
tmp_dir.path().to_str().unwrap(),
AvroReadOptions::default().schema(schema.as_ref()),
)
.await?;
}
"arrow" => {
session_ctx
.register_arrow(
"t",
tmp_dir.path().to_str().unwrap(),
ArrowReadOptions::default().schema(schema.as_ref()),
)
.await?;
}
_ => panic!("Unrecognized file extension {file_type_ext}"),
}
// Create and register the source table with the provided schema and inserted data
let source_table = Arc::new(MemTable::try_new(
schema.clone(),
vec![vec![batch.clone(), batch.clone()]],
)?);
session_ctx.register_table("source", source_table.clone())?;
// Convert the source table into a provider so that it can be used in a query
let source = provider_as_source(source_table);
let target = session_ctx.table_provider("t").await?;
let target = Arc::new(DefaultTableSource::new(target));
// Create a table scan logical plan to read from the source table
let scan_plan = LogicalPlanBuilder::scan("source", source, None)?
.filter(filter_predicate)?
.build()?;
// Since logical plan contains a filter, increasing parallelism is helpful.
// Therefore, we will have 8 partitions in the final plan.
// Create an insert plan to insert the source data into the initial table
let insert_into_table =
LogicalPlanBuilder::insert_into(scan_plan, "t", target, InsertOp::Append)?
.build()?;
// Create a physical plan from the insert plan
let plan = session_ctx
.state()
.create_physical_plan(&insert_into_table)
.await?;
// Execute the physical plan and collect the results
let res = collect(plan, session_ctx.task_ctx()).await?;
// Insert returns the number of rows written, in our case this would be 6.
insta::allow_duplicates! {insta::assert_snapshot!(batches_to_string(&res),@r"
+-------+
| count |
+-------+
| 20 |
+-------+
");}
// Read the records in the table
let batches = session_ctx
.sql("select count(*) as count from t")
.await?
.collect()
.await?;
insta::allow_duplicates! {insta::assert_snapshot!(batches_to_string(&batches),@r"
+-------+
| count |
+-------+
| 20 |
+-------+
");}
// Assert that `target_partition_number` many files were added to the table.
let num_files = tmp_dir.path().read_dir()?.count();
assert_eq!(num_files, expected_n_files_per_insert);
// Create a physical plan from the insert plan