1use std::sync::Arc;
6
7use datafusion_common::{DataFusionError, Result, TableReference};
8use datafusion_execution::cache::cache_manager::CachedFileList;
9use datafusion_execution::cache::cache_manager::TableScopedPath;
10use datafusion_execution::object_store::ObjectStoreUrl;
11use datafusion_session::Session;
12
13use futures::stream::BoxStream;
14use futures::{StreamExt, TryStreamExt};
15use glob::Pattern;
16use itertools::Itertools;
17use log::debug;
18use object_store::path::DELIMITER;
19use object_store::path::Path;
20use object_store::{ObjectMeta, ObjectStore, ObjectStoreExt};
21use url::Url;
22
23#[derive(Debug, Clone, Eq, PartialEq, Hash)]
26pub struct ListingTableUrl {
27 url: Url,
29 prefix: Path,
31 glob: Option<Pattern>,
33 table_ref: Option<TableReference>,
35}
36
37impl ListingTableUrl {
38 pub fn parse(s: impl AsRef<str>) -> Result<Self> {
94 let s = s.as_ref();
95
96 #[cfg(not(target_arch = "wasm32"))]
98 if std::path::Path::new(s).is_absolute() {
99 return Self::parse_path(s);
100 }
101
102 match Url::parse(s) {
103 Ok(url) => Self::try_new(url, None),
104 #[cfg(not(target_arch = "wasm32"))]
105 Err(url::ParseError::RelativeUrlWithoutBase) => Self::parse_path(s),
106 Err(e) => Err(DataFusionError::External(Box::new(e))),
107 }
108 }
109
110 #[cfg(not(target_arch = "wasm32"))]
112 fn parse_path(s: &str) -> Result<Self> {
113 let (path, glob) = match split_glob_expression(s) {
114 Some((prefix, glob)) => {
115 let glob = Pattern::new(glob)
116 .map_err(|e| DataFusionError::External(Box::new(e)))?;
117 (prefix, Some(glob))
118 }
119 None => (s, None),
120 };
121
122 let url = url_from_filesystem_path(path).ok_or_else(|| {
123 DataFusionError::External(
124 format!("Failed to convert path to URL: {path}").into(),
125 )
126 })?;
127
128 Self::try_new(url, glob)
129 }
130
131 pub fn try_new(url: Url, glob: Option<Pattern>) -> Result<Self> {
138 let prefix = Path::from_url_path(url.path())?;
139 Ok(Self {
140 url,
141 prefix,
142 glob,
143 table_ref: None,
144 })
145 }
146
147 pub fn scheme(&self) -> &str {
149 self.url.scheme()
150 }
151
152 pub fn prefix(&self) -> &Path {
157 &self.prefix
158 }
159
160 pub fn contains(&self, path: &Path, ignore_subdirectory: bool) -> bool {
162 let Some(all_segments) = self.strip_prefix(path) else {
163 return false;
164 };
165
166 let mut segments = all_segments.filter(|s| !s.contains('='));
169
170 match &self.glob {
171 Some(glob) => {
172 if ignore_subdirectory {
173 segments
174 .next()
175 .is_some_and(|file_name| glob.matches(file_name))
176 } else {
177 let stripped = segments.join(DELIMITER);
178 glob.matches(&stripped)
179 }
180 }
181 None if ignore_subdirectory => segments.count() <= 1,
185 None => true,
187 }
188 }
189
190 pub fn is_collection(&self) -> bool {
192 self.url.path().ends_with(DELIMITER)
193 }
194
195 pub fn file_extension(&self) -> Option<&str> {
208 if let Some(mut segments) = self.url.path_segments()
209 && let Some(last_segment) = segments.next_back()
210 && last_segment.contains('.')
211 && !last_segment.ends_with('.')
212 {
213 return last_segment.split('.').next_back();
214 }
215
216 None
217 }
218
219 pub fn strip_prefix<'a, 'b: 'a>(
222 &'a self,
223 path: &'b Path,
224 ) -> Option<impl Iterator<Item = &'b str> + 'a> {
225 let mut stripped = path.as_ref().strip_prefix(self.prefix.as_ref())?;
226 if !stripped.is_empty() && !self.prefix.as_ref().is_empty() {
227 stripped = stripped.strip_prefix(DELIMITER)?;
228 }
229 Some(stripped.split_terminator(DELIMITER))
230 }
231
232 pub async fn list_prefixed_files<'a>(
235 &'a self,
236 ctx: &'a dyn Session,
237 store: &'a dyn ObjectStore,
238 prefix: Option<Path>,
239 file_extension: &'a str,
240 ) -> Result<BoxStream<'a, Result<ObjectMeta>>> {
241 let exec_options = &ctx.config_options().execution;
242 let ignore_subdirectory = exec_options.listing_table_ignore_subdirectory;
243
244 let full_prefix = if let Some(ref p) = prefix {
246 let mut parts = self.prefix.parts().collect::<Vec<_>>();
247 parts.extend(p.parts());
248 Path::from_iter(parts)
249 } else {
250 self.prefix.clone()
251 };
252
253 let list: BoxStream<'a, Result<ObjectMeta>> = if self.is_collection() {
254 list_with_cache(
255 ctx,
256 store,
257 self.table_ref.as_ref(),
258 &self.prefix,
259 prefix.as_ref(),
260 )
261 .await?
262 } else {
263 match store.head(&full_prefix).await {
264 Ok(meta) => futures::stream::once(async { Ok(meta) })
265 .map_err(|e| DataFusionError::ObjectStore(Box::new(e)))
266 .boxed(),
267 Err(object_store::Error::NotFound { .. }) => {
270 list_with_cache(
271 ctx,
272 store,
273 self.table_ref.as_ref(),
274 &self.prefix,
275 prefix.as_ref(),
276 )
277 .await?
278 }
279 Err(e) => return Err(e.into()),
280 }
281 };
282
283 Ok(list
284 .try_filter(move |meta| {
285 let path = &meta.location;
286 let extension_match = path.as_ref().ends_with(file_extension);
287 let glob_match = self.contains(path, ignore_subdirectory);
288 futures::future::ready(extension_match && glob_match)
289 })
290 .boxed())
291 }
292
293 pub async fn list_all_files<'a>(
295 &'a self,
296 ctx: &'a dyn Session,
297 store: &'a dyn ObjectStore,
298 file_extension: &'a str,
299 ) -> Result<BoxStream<'a, Result<ObjectMeta>>> {
300 self.list_prefixed_files(ctx, store, None, file_extension)
301 .await
302 }
303
304 pub fn as_str(&self) -> &str {
306 self.as_ref()
307 }
308
309 pub fn object_store(&self) -> ObjectStoreUrl {
311 let url = &self.url[url::Position::BeforeScheme..url::Position::BeforePath];
312 ObjectStoreUrl::parse(url).unwrap()
313 }
314
315 pub fn is_folder(&self) -> bool {
317 self.url.scheme() == "file" && self.is_collection()
318 }
319
320 pub fn get_url(&self) -> &Url {
322 &self.url
323 }
324
325 pub fn get_glob(&self) -> &Option<Pattern> {
327 &self.glob
328 }
329
330 pub fn with_glob(mut self, glob: &str) -> Result<Self> {
332 self.glob =
333 Some(Pattern::new(glob).map_err(|e| DataFusionError::External(Box::new(e)))?);
334 Ok(self)
335 }
336
337 pub fn with_table_ref(mut self, table_ref: TableReference) -> Self {
339 self.table_ref = Some(table_ref);
340 self
341 }
342
343 pub fn get_table_ref(&self) -> &Option<TableReference> {
345 &self.table_ref
346 }
347}
348
349async fn list_with_cache<'b>(
361 ctx: &'b dyn Session,
362 store: &'b dyn ObjectStore,
363 table_ref: Option<&TableReference>,
364 table_base_path: &Path,
365 prefix: Option<&Path>,
366) -> Result<BoxStream<'b, Result<ObjectMeta>>> {
367 let full_prefix = match prefix {
369 Some(p) => {
370 let mut parts: Vec<_> = table_base_path.parts().collect();
371 parts.extend(p.parts());
372 Path::from_iter(parts)
373 }
374 None => table_base_path.clone(),
375 };
376
377 match ctx.runtime_env().cache_manager.get_list_files_cache() {
378 None => Ok(store
379 .list(Some(&full_prefix))
380 .map(|res| res.map_err(|e| DataFusionError::ObjectStore(Box::new(e))))
381 .boxed()),
382 Some(cache) => {
383 let filter_prefix = prefix.is_some().then(|| full_prefix.clone());
384
385 let table_scoped_base_path = TableScopedPath {
386 table: table_ref.cloned(),
387 path: table_base_path.clone(),
388 };
389 let table_scoped_list_path = TableScopedPath {
390 table: table_ref.cloned(),
391 path: full_prefix.clone(),
392 };
393
394 let vec = if let Some(cached) = cache.get(&table_scoped_base_path) {
395 debug!("Hit list files cache");
396 cached.files_matching_prefix(&filter_prefix)
397 } else if let Some(cached) = cache.get(&table_scoped_list_path) {
398 debug!("Hit list files cache for requested path");
399 cached.files_matching_prefix(&None)
400 } else {
401 let mut vec = store
402 .list(Some(&full_prefix))
403 .try_collect::<Vec<ObjectMeta>>()
404 .await?;
405 vec.shrink_to_fit(); let cached: CachedFileList = vec.into();
407 let result = cached.files_matching_prefix(&None);
408 cache.put(&table_scoped_list_path, cached);
409 result
410 };
411 Ok(
412 futures::stream::iter(Arc::unwrap_or_clone(vec).into_iter().map(Ok))
413 .boxed(),
414 )
415 }
416 }
417}
418
419#[cfg(not(target_arch = "wasm32"))]
421fn url_from_filesystem_path(s: &str) -> Option<Url> {
422 let path = std::path::Path::new(s);
423 let is_dir = match path.exists() {
424 true => path.is_dir(),
425 false => std::path::is_separator(s.chars().last()?),
427 };
428
429 let from_absolute_path = |p| {
430 let first = match is_dir {
431 true => Url::from_directory_path(p).ok(),
432 false => Url::from_file_path(p).ok(),
433 }?;
434
435 Url::parse(first.as_str()).ok()
438 };
439
440 if path.is_absolute() {
441 return from_absolute_path(path);
442 }
443
444 let absolute = std::env::current_dir().ok()?.join(path);
445 from_absolute_path(&absolute)
446}
447
448impl AsRef<str> for ListingTableUrl {
449 fn as_ref(&self) -> &str {
450 self.url.as_ref()
451 }
452}
453
454impl AsRef<Url> for ListingTableUrl {
455 fn as_ref(&self) -> &Url {
456 &self.url
457 }
458}
459
460impl std::fmt::Display for ListingTableUrl {
461 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
462 self.as_str().fmt(f)
463 }
464}
465
466#[cfg(not(target_arch = "wasm32"))]
467const GLOB_START_CHARS: [char; 3] = ['?', '*', '['];
468
469#[cfg(not(target_arch = "wasm32"))]
475fn split_glob_expression(path: &str) -> Option<(&str, &str)> {
476 let mut last_separator = 0;
477
478 for (byte_idx, char) in path.char_indices() {
479 if GLOB_START_CHARS.contains(&char) {
480 if last_separator == 0 {
481 return Some((".", path));
482 }
483 return Some(path.split_at(last_separator));
484 }
485
486 if std::path::is_separator(char) {
487 last_separator = byte_idx + char.len_utf8();
488 }
489 }
490 None
491}
492
493#[cfg(test)]
494mod tests {
495 use super::*;
496 use async_trait::async_trait;
497 use bytes::Bytes;
498 use datafusion_common::DFSchema;
499 use datafusion_common::config::TableOptions;
500 use datafusion_execution::TaskContext;
501 use datafusion_execution::config::SessionConfig;
502 use datafusion_execution::runtime_env::RuntimeEnv;
503 use datafusion_expr::execution_props::ExecutionProps;
504 use datafusion_expr::registry::ExtensionTypeRegistryRef;
505 use datafusion_expr::{
506 AggregateUDF, Expr, HigherOrderUDF, LogicalPlan, ScalarUDF, WindowUDF,
507 };
508 use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
509 use datafusion_physical_plan::ExecutionPlan;
510 use datafusion_session::{CatalogProviderList, EmptyCatalogProviderList};
511 use object_store::{
512 CopyOptions, GetOptions, GetResult, ListResult, MultipartUpload,
513 PutMultipartOptions, PutPayload,
514 };
515 use std::any::Any;
516 use std::collections::HashMap;
517 use std::ops::Range;
518 use std::sync::Mutex;
519 use tempfile::tempdir;
520
521 #[test]
522 fn test_prefix_path() {
523 let root = std::env::current_dir().unwrap();
524 let root = root.to_string_lossy();
525
526 let url = ListingTableUrl::parse(root).unwrap();
527 let child = url.prefix.clone().join("partition").join("file");
528
529 let prefix: Vec<_> = url.strip_prefix(&child).unwrap().collect();
530 assert_eq!(prefix, vec!["partition", "file"]);
531
532 let url = ListingTableUrl::parse("file:///").unwrap();
533 let child = Path::parse("/foo/bar").unwrap();
534 let prefix: Vec<_> = url.strip_prefix(&child).unwrap().collect();
535 assert_eq!(prefix, vec!["foo", "bar"]);
536
537 let url = ListingTableUrl::parse("file:///foo").unwrap();
538 let child = Path::parse("/foob/bar").unwrap();
539 assert!(url.strip_prefix(&child).is_none());
540
541 let url = ListingTableUrl::parse("file:///foo/file").unwrap();
542 let child = Path::parse("/foo/file").unwrap();
543 assert_eq!(url.strip_prefix(&child).unwrap().count(), 0);
544
545 let url = ListingTableUrl::parse("file:///foo/ bar").unwrap();
546 assert_eq!(url.prefix.as_ref(), "foo/ bar");
547
548 let url = ListingTableUrl::parse("file:///foo/bar?").unwrap();
549 assert_eq!(url.prefix.as_ref(), "foo/bar");
550
551 let url = ListingTableUrl::parse("file:///foo/😺").unwrap();
552 assert_eq!(url.prefix.as_ref(), "foo/😺");
553
554 let url = ListingTableUrl::parse("file:///foo/bar%2Efoo").unwrap();
555 assert_eq!(url.prefix.as_ref(), "foo/bar.foo");
556
557 let url = ListingTableUrl::parse("file:///foo/bar%2Efoo").unwrap();
558 assert_eq!(url.prefix.as_ref(), "foo/bar.foo");
559
560 let url = ListingTableUrl::parse("file:///foo/bar%252Ffoo").unwrap();
561 assert_eq!(url.prefix.as_ref(), "foo/bar%2Ffoo");
562
563 let url = ListingTableUrl::parse("file:///foo/a%252Fb.txt").unwrap();
564 assert_eq!(url.prefix.as_ref(), "foo/a%2Fb.txt");
565
566 let dir = tempdir().unwrap();
567 let path = dir.path().join("bar%2Ffoo");
568 std::fs::File::create(&path).unwrap();
569
570 let url = ListingTableUrl::parse(path.to_str().unwrap()).unwrap();
571 assert!(url.prefix.as_ref().ends_with("bar%2Ffoo"), "{}", url.prefix);
572
573 let url = ListingTableUrl::parse("file:///foo/../a%252Fb.txt").unwrap();
574 assert_eq!(url.prefix.as_ref(), "a%2Fb.txt");
575
576 let url =
577 ListingTableUrl::parse("file:///foo/./bar/../../baz/./test.txt").unwrap();
578 assert_eq!(url.prefix.as_ref(), "baz/test.txt");
579
580 let workdir = std::env::current_dir().unwrap();
581 let t = workdir.join("non-existent");
582 let a = ListingTableUrl::parse(t.to_str().unwrap()).unwrap();
583 let b = ListingTableUrl::parse("non-existent").unwrap();
584 assert_eq!(a, b);
585 assert!(a.prefix.as_ref().ends_with("non-existent"));
586
587 let t = workdir.parent().unwrap();
588 let a = ListingTableUrl::parse(t.to_str().unwrap()).unwrap();
589 let b = ListingTableUrl::parse("..").unwrap();
590 assert_eq!(a, b);
591
592 let t = t.join("bar");
593 let a = ListingTableUrl::parse(t.to_str().unwrap()).unwrap();
594 let b = ListingTableUrl::parse("../bar").unwrap();
595 assert_eq!(a, b);
596 assert!(a.prefix.as_ref().ends_with("bar"));
597
598 let t = t.join(".").join("foo").join("..").join("baz");
599 let a = ListingTableUrl::parse(t.to_str().unwrap()).unwrap();
600 let b = ListingTableUrl::parse("../bar/./foo/../baz").unwrap();
601 assert_eq!(a, b);
602 assert!(a.prefix.as_ref().ends_with("bar/baz"));
603 }
604
605 #[test]
606 fn test_prefix_s3() {
607 let url = ListingTableUrl::parse("s3://bucket/foo/bar").unwrap();
608 assert_eq!(url.prefix.as_ref(), "foo/bar");
609
610 let path = Path::from("foo/bar/partition/foo.parquet");
611 let prefix: Vec<_> = url.strip_prefix(&path).unwrap().collect();
612 assert_eq!(prefix, vec!["partition", "foo.parquet"]);
613
614 let path = Path::from("other/bar/partition/foo.parquet");
615 assert!(url.strip_prefix(&path).is_none());
616 }
617
618 #[test]
619 fn test_split_glob() {
620 fn test(input: &str, expected: Option<(&str, &str)>) {
621 assert_eq!(
622 split_glob_expression(input),
623 expected,
624 "testing split_glob_expression with {input}"
625 );
626 }
627
628 test("/", None);
630 test("/a.txt", None);
631 test("/a", None);
632 test("/a/", None);
633 test("/a/b", None);
634 test("/a/b/", None);
635 test("/a/b.txt", None);
636 test("/a/b/c.txt", None);
637 test("*.txt", Some((".", "*.txt")));
639 test("/*.txt", Some(("/", "*.txt")));
640 test("/a/*b.txt", Some(("/a/", "*b.txt")));
641 test("/a/*/b.txt", Some(("/a/", "*/b.txt")));
642 test("/a/b/[123]/file*.txt", Some(("/a/b/", "[123]/file*.txt")));
643 test("/a/b*.txt", Some(("/a/", "b*.txt")));
644 test("/a/b/**/c*.txt", Some(("/a/b/", "**/c*.txt")));
645
646 test(
648 "/a/b/c//alltypes_plain*.parquet",
649 Some(("/a/b/c//", "alltypes_plain*.parquet")),
650 );
651 }
652
653 #[test]
654 fn test_is_collection() {
655 fn test(input: &str, expected: bool, message: &str) {
656 let url = ListingTableUrl::parse(input).unwrap();
657 assert_eq!(url.is_collection(), expected, "{message}");
658 }
659
660 test("https://a.b.c/path/", true, "path ends with / - collection");
661 test(
662 "https://a.b.c/path/?a=b",
663 true,
664 "path ends with / - with query args - collection",
665 );
666 test(
667 "https://a.b.c/path?a=b/",
668 false,
669 "path not ends with / - query ends with / - not collection",
670 );
671 test(
672 "https://a.b.c/path/#a=b",
673 true,
674 "path ends with / - with fragment - collection",
675 );
676 test(
677 "https://a.b.c/path#a=b/",
678 false,
679 "path not ends with / - fragment ends with / - not collection",
680 );
681 }
682
683 #[test]
684 fn test_file_extension() {
685 fn test(input: &str, expected: Option<&str>, message: &str) {
686 let url = ListingTableUrl::parse(input).unwrap();
687 assert_eq!(url.file_extension(), expected, "{message}");
688 }
689
690 test("https://a.b.c/path/", None, "path ends with / - not a file");
691 test(
692 "https://a.b.c/path/?a=b",
693 None,
694 "path ends with / - with query args - not a file",
695 );
696 test(
697 "https://a.b.c/path?a=b/",
698 None,
699 "path not ends with / - query ends with / but no file extension",
700 );
701 test(
702 "https://a.b.c/path/#a=b",
703 None,
704 "path ends with / - with fragment - not a file",
705 );
706 test(
707 "https://a.b.c/path#a=b/",
708 None,
709 "path not ends with / - fragment ends with / but no file extension",
710 );
711 test(
712 "file///some/path/",
713 None,
714 "file path ends with / - not a file",
715 );
716 test(
717 "file///some/path/file",
718 None,
719 "file path does not end with - no extension",
720 );
721 test(
722 "file///some/path/file.",
723 None,
724 "file path ends with . - no value after .",
725 );
726 test(
727 "file///some/path/file.ext",
728 Some("ext"),
729 "file path ends with .ext - extension is ext",
730 );
731 }
732
733 #[tokio::test]
734 async fn test_list_files() -> Result<()> {
735 let store =
736 MockObjectStore::with_forbidden_paths(vec!["forbidden/e.parquet".into()]);
737
738 create_file(&store, "a.parquet").await;
740 create_file(&store, "/t/b.parquet").await;
741 create_file(&store, "/t/c.csv").await;
742 create_file(&store, "/t/d.csv").await;
743
744 create_file(&store, "/forbidden/e.parquet").await;
746
747 assert_eq!(
748 list_all_files("/", &store, "parquet").await?,
749 vec!["a.parquet"],
750 );
751
752 assert_eq!(
754 list_all_files("/t/", &store, "parquet").await?,
755 vec!["t/b.parquet"],
756 );
757 assert_eq!(
758 list_all_files("/t", &store, "parquet").await?,
759 vec!["t/b.parquet"],
760 );
761
762 assert_eq!(
764 list_all_files("/t", &store, "csv").await?,
765 vec!["t/c.csv", "t/d.csv"],
766 );
767 assert_eq!(
768 list_all_files("/t/", &store, "csv").await?,
769 vec!["t/c.csv", "t/d.csv"],
770 );
771
772 assert_eq!(
774 list_all_files("/NonExisting", &store, "csv").await?,
775 vec![] as Vec<String>
776 );
777 assert_eq!(
778 list_all_files("/NonExisting/", &store, "csv").await?,
779 vec![] as Vec<String>
780 );
781
782 let Err(DataFusionError::ObjectStore(err)) =
784 list_all_files("/forbidden/e.parquet", &store, "parquet").await
785 else {
786 panic!("Expected ObjectStore error");
787 };
788
789 let object_store::Error::PermissionDenied { .. } = &*err else {
790 panic!("Expected PermissionDenied error");
791 };
792
793 create_file(&store, "/data/a=1/file1.parquet").await;
795 create_file(&store, "/data/a=1/b=100/file2.parquet").await;
796 create_file(&store, "/data/a=2/b=200/file3.parquet").await;
797 create_file(&store, "/data/a=2/b=200/file4.csv").await;
798
799 assert_eq!(
800 list_prefixed_files("/data/", &store, Some(Path::from("a=1")), "parquet")
801 .await?,
802 vec!["data/a=1/b=100/file2.parquet", "data/a=1/file1.parquet"],
803 );
804
805 assert_eq!(
806 list_prefixed_files(
807 "/data/",
808 &store,
809 Some(Path::from("a=1/b=100")),
810 "parquet"
811 )
812 .await?,
813 vec!["data/a=1/b=100/file2.parquet"],
814 );
815
816 assert_eq!(
817 list_prefixed_files("/data/", &store, Some(Path::from("a=2")), "parquet")
818 .await?,
819 vec!["data/a=2/b=200/file3.parquet"],
820 );
821
822 Ok(())
823 }
824
825 #[tokio::test]
831 async fn test_cache_path_equivalence() -> Result<()> {
832 use datafusion_execution::runtime_env::RuntimeEnvBuilder;
833
834 let store = MockObjectStore::new();
835
836 create_file(&store, "/table/year=2023/data1.parquet").await;
838 create_file(&store, "/table/year=2023/month=01/data2.parquet").await;
839 create_file(&store, "/table/year=2024/data3.parquet").await;
840 create_file(&store, "/table/year=2024/month=06/data4.parquet").await;
841 create_file(&store, "/table/year=2024/month=12/data5.parquet").await;
842
843 let session_no_cache = MockSession::new();
845
846 let runtime_with_cache = RuntimeEnvBuilder::new()
848 .with_object_list_cache_limit(1024 * 1024) .build_arc()?;
850 let session_with_cache = MockSession::with_runtime_env(runtime_with_cache);
851
852 let test_cases = vec![
854 ("/table/", None, "full table listing"),
855 (
856 "/table/",
857 Some(Path::from("year=2023")),
858 "single partition filter",
859 ),
860 (
861 "/table/",
862 Some(Path::from("year=2024")),
863 "different partition filter",
864 ),
865 (
866 "/table/",
867 Some(Path::from("year=2024/month=06")),
868 "nested partition filter",
869 ),
870 (
871 "/table/",
872 Some(Path::from("year=2025")),
873 "non-existent partition",
874 ),
875 ];
876
877 for (url_str, prefix, description) in test_cases {
878 let url = ListingTableUrl::parse(url_str)?;
879
880 let mut results_no_cache: Vec<String> = url
882 .list_prefixed_files(&session_no_cache, &store, prefix.clone(), "parquet")
883 .await?
884 .try_collect::<Vec<_>>()
885 .await?
886 .into_iter()
887 .map(|m| m.location.to_string())
888 .collect();
889 results_no_cache.sort();
890
891 let mut results_with_cache_miss: Vec<String> = url
893 .list_prefixed_files(
894 &session_with_cache,
895 &store,
896 prefix.clone(),
897 "parquet",
898 )
899 .await?
900 .try_collect::<Vec<_>>()
901 .await?
902 .into_iter()
903 .map(|m| m.location.to_string())
904 .collect();
905 results_with_cache_miss.sort();
906
907 let mut results_with_cache_hit: Vec<String> = url
909 .list_prefixed_files(&session_with_cache, &store, prefix, "parquet")
910 .await?
911 .try_collect::<Vec<_>>()
912 .await?
913 .into_iter()
914 .map(|m| m.location.to_string())
915 .collect();
916 results_with_cache_hit.sort();
917
918 assert_eq!(
920 results_no_cache, results_with_cache_miss,
921 "Cache miss path should match non-cached path for: {description}"
922 );
923 assert_eq!(
924 results_no_cache, results_with_cache_hit,
925 "Cache hit path should match non-cached path for: {description}"
926 );
927 }
928
929 Ok(())
930 }
931
932 #[tokio::test]
933 async fn test_cache_miss_with_prefix_lists_prefixed_path() -> Result<()> {
934 use datafusion_execution::runtime_env::RuntimeEnvBuilder;
935
936 let store = MockObjectStore::new();
937 create_file(&store, "/table/year=2023/data1.parquet").await;
938 create_file(&store, "/table/year=2024/month=06/data2.parquet").await;
939 create_file(&store, "/table/year=2024/month=12/data3.parquet").await;
940
941 let runtime = RuntimeEnvBuilder::new()
942 .with_object_list_cache_limit(1024 * 1024)
943 .build_arc()?;
944 let session = MockSession::with_runtime_env(runtime);
945 let url = ListingTableUrl::parse("/table/")?;
946 let prefix = Path::from("year=2024/month=06");
947
948 let results: Vec<String> = url
949 .list_prefixed_files(&session, &store, Some(prefix.clone()), "parquet")
950 .await?
951 .try_collect::<Vec<_>>()
952 .await?
953 .into_iter()
954 .map(|m| m.location.to_string())
955 .collect();
956
957 assert_eq!(results, vec!["table/year=2024/month=06/data2.parquet"]);
958 assert_eq!(
959 store.list_prefixes(),
960 vec![Some(Path::from("table/year=2024/month=06"))]
961 );
962
963 let results: Vec<String> = url
964 .list_prefixed_files(&session, &store, Some(prefix), "parquet")
965 .await?
966 .try_collect::<Vec<_>>()
967 .await?
968 .into_iter()
969 .map(|m| m.location.to_string())
970 .collect();
971
972 assert_eq!(results, vec!["table/year=2024/month=06/data2.parquet"]);
973 assert_eq!(
974 store.list_prefixes(),
975 vec![Some(Path::from("table/year=2024/month=06"))]
976 );
977
978 Ok(())
979 }
980
981 #[tokio::test]
982 async fn test_prefix_cache_does_not_satisfy_broader_listing() -> Result<()> {
983 use datafusion_execution::runtime_env::RuntimeEnvBuilder;
984
985 let store = MockObjectStore::new();
986 create_file(&store, "/sales/region=US/q1/data.parquet").await;
987 create_file(&store, "/sales/region=US/q2/data.parquet").await;
988 create_file(&store, "/sales/region=EU/q1.parquet").await;
989
990 let runtime = RuntimeEnvBuilder::new()
991 .with_object_list_cache_limit(1024 * 1024)
992 .build_arc()?;
993 let mut session = MockSession::with_runtime_env(runtime);
994 session
995 .config
996 .options_mut()
997 .execution
998 .listing_table_ignore_subdirectory = false;
999 let url = ListingTableUrl::parse("/sales/")?;
1000
1001 let q1_results: Vec<String> = url
1002 .list_prefixed_files(
1003 &session,
1004 &store,
1005 Some(Path::from("region=US/q1")),
1006 "parquet",
1007 )
1008 .await?
1009 .try_collect::<Vec<_>>()
1010 .await?
1011 .into_iter()
1012 .map(|m| m.location.to_string())
1013 .collect();
1014 assert_eq!(q1_results, vec!["sales/region=US/q1/data.parquet"]);
1015
1016 let us_results: Vec<String> = url
1017 .list_prefixed_files(
1018 &session,
1019 &store,
1020 Some(Path::from("region=US")),
1021 "parquet",
1022 )
1023 .await?
1024 .try_collect::<Vec<_>>()
1025 .await?
1026 .into_iter()
1027 .map(|m| m.location.to_string())
1028 .collect();
1029 assert_eq!(
1030 us_results,
1031 vec![
1032 "sales/region=US/q1/data.parquet",
1033 "sales/region=US/q2/data.parquet"
1034 ]
1035 );
1036
1037 let full_results: Vec<String> = url
1038 .list_prefixed_files(&session, &store, None, "parquet")
1039 .await?
1040 .try_collect::<Vec<_>>()
1041 .await?
1042 .into_iter()
1043 .map(|m| m.location.to_string())
1044 .collect();
1045 assert_eq!(full_results.len(), 3);
1046 assert_eq!(
1047 store.list_prefixes(),
1048 vec![
1049 Some(Path::from("sales/region=US/q1")),
1050 Some(Path::from("sales/region=US")),
1051 Some(Path::from("sales"))
1052 ]
1053 );
1054
1055 Ok(())
1056 }
1057
1058 #[tokio::test]
1060 async fn test_cache_serves_partition_from_full_listing() -> Result<()> {
1061 use datafusion_execution::runtime_env::RuntimeEnvBuilder;
1062
1063 let store = MockObjectStore::new();
1064
1065 create_file(&store, "/sales/region=US/q1.parquet").await;
1067 create_file(&store, "/sales/region=US/q2.parquet").await;
1068 create_file(&store, "/sales/region=EU/q1.parquet").await;
1069
1070 let runtime = RuntimeEnvBuilder::new()
1072 .with_object_list_cache_limit(1024 * 1024) .build_arc()?;
1074 let session = MockSession::with_runtime_env(runtime);
1075
1076 let url = ListingTableUrl::parse("/sales/")?;
1077
1078 let full_results: Vec<String> = url
1080 .list_prefixed_files(&session, &store, None, "parquet")
1081 .await?
1082 .try_collect::<Vec<_>>()
1083 .await?
1084 .into_iter()
1085 .map(|m| m.location.to_string())
1086 .collect();
1087 assert_eq!(full_results.len(), 3);
1088 assert_eq!(store.list_prefixes(), vec![Some(Path::from("sales"))]);
1089
1090 let mut us_results: Vec<String> = url
1092 .list_prefixed_files(
1093 &session,
1094 &store,
1095 Some(Path::from("region=US")),
1096 "parquet",
1097 )
1098 .await?
1099 .try_collect::<Vec<_>>()
1100 .await?
1101 .into_iter()
1102 .map(|m| m.location.to_string())
1103 .collect();
1104 us_results.sort();
1105
1106 assert_eq!(
1107 us_results,
1108 vec!["sales/region=US/q1.parquet", "sales/region=US/q2.parquet"]
1109 );
1110 assert_eq!(store.list_prefixes(), vec![Some(Path::from("sales"))]);
1111
1112 let eu_results: Vec<String> = url
1114 .list_prefixed_files(
1115 &session,
1116 &store,
1117 Some(Path::from("region=EU")),
1118 "parquet",
1119 )
1120 .await?
1121 .try_collect::<Vec<_>>()
1122 .await?
1123 .into_iter()
1124 .map(|m| m.location.to_string())
1125 .collect();
1126
1127 assert_eq!(eu_results, vec!["sales/region=EU/q1.parquet"]);
1128 assert_eq!(store.list_prefixes(), vec![Some(Path::from("sales"))]);
1129
1130 Ok(())
1131 }
1132
1133 async fn create_file(object_store: &dyn ObjectStore, path: &str) {
1135 object_store
1136 .put(&Path::from(path), PutPayload::from_static(b"hello world"))
1137 .await
1138 .expect("failed to create test file");
1139 }
1140
1141 async fn list_all_files(
1145 url: &str,
1146 store: &dyn ObjectStore,
1147 file_extension: &str,
1148 ) -> Result<Vec<String>> {
1149 try_list_prefixed_files(url, store, None, file_extension).await
1150 }
1151
1152 async fn list_prefixed_files(
1156 url: &str,
1157 store: &dyn ObjectStore,
1158 prefix: Option<Path>,
1159 file_extension: &str,
1160 ) -> Result<Vec<String>> {
1161 try_list_prefixed_files(url, store, prefix, file_extension).await
1162 }
1163
1164 async fn try_list_prefixed_files(
1166 url: &str,
1167 store: &dyn ObjectStore,
1168 prefix: Option<Path>,
1169 file_extension: &str,
1170 ) -> Result<Vec<String>> {
1171 let session = MockSession::new();
1172 let url = ListingTableUrl::parse(url)?;
1173 let files = url
1174 .list_prefixed_files(&session, store, prefix, file_extension)
1175 .await?
1176 .try_collect::<Vec<_>>()
1177 .await?
1178 .into_iter()
1179 .map(|meta| meta.location.as_ref().to_string())
1180 .collect();
1181 Ok(files)
1182 }
1183
1184 #[derive(Debug)]
1185 struct MockObjectStore {
1186 in_mem: object_store::memory::InMemory,
1187 forbidden_paths: Vec<Path>,
1188 list_prefixes: Arc<Mutex<Vec<Option<Path>>>>,
1189 }
1190
1191 impl MockObjectStore {
1192 fn new() -> Self {
1193 Self::with_forbidden_paths(vec![])
1194 }
1195
1196 fn with_forbidden_paths(forbidden_paths: Vec<Path>) -> Self {
1197 Self {
1198 in_mem: object_store::memory::InMemory::new(),
1199 forbidden_paths,
1200 list_prefixes: Default::default(),
1201 }
1202 }
1203
1204 fn list_prefixes(&self) -> Vec<Option<Path>> {
1205 self.list_prefixes.lock().unwrap().clone()
1206 }
1207 }
1208
1209 impl std::fmt::Display for MockObjectStore {
1210 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1211 self.in_mem.fmt(f)
1212 }
1213 }
1214
1215 #[async_trait]
1216 impl ObjectStore for MockObjectStore {
1217 async fn put_opts(
1218 &self,
1219 location: &Path,
1220 payload: PutPayload,
1221 opts: object_store::PutOptions,
1222 ) -> object_store::Result<object_store::PutResult> {
1223 self.in_mem.put_opts(location, payload, opts).await
1224 }
1225
1226 async fn put_multipart_opts(
1227 &self,
1228 location: &Path,
1229 opts: PutMultipartOptions,
1230 ) -> object_store::Result<Box<dyn MultipartUpload>> {
1231 self.in_mem.put_multipart_opts(location, opts).await
1232 }
1233
1234 async fn get_opts(
1235 &self,
1236 location: &Path,
1237 options: GetOptions,
1238 ) -> object_store::Result<GetResult> {
1239 if options.head && self.forbidden_paths.contains(location) {
1240 Err(object_store::Error::PermissionDenied {
1241 path: location.to_string(),
1242 source: "forbidden".into(),
1243 })
1244 } else {
1245 self.in_mem.get_opts(location, options).await
1246 }
1247 }
1248
1249 async fn get_ranges(
1250 &self,
1251 location: &Path,
1252 ranges: &[Range<u64>],
1253 ) -> object_store::Result<Vec<Bytes>> {
1254 self.in_mem.get_ranges(location, ranges).await
1255 }
1256
1257 fn delete_stream(
1258 &self,
1259 locations: BoxStream<'static, object_store::Result<Path>>,
1260 ) -> BoxStream<'static, object_store::Result<Path>> {
1261 self.in_mem.delete_stream(locations)
1262 }
1263
1264 fn list(
1265 &self,
1266 prefix: Option<&Path>,
1267 ) -> BoxStream<'static, object_store::Result<ObjectMeta>> {
1268 self.list_prefixes.lock().unwrap().push(prefix.cloned());
1269 self.in_mem.list(prefix)
1270 }
1271
1272 async fn list_with_delimiter(
1273 &self,
1274 prefix: Option<&Path>,
1275 ) -> object_store::Result<ListResult> {
1276 self.in_mem.list_with_delimiter(prefix).await
1277 }
1278
1279 async fn copy_opts(
1280 &self,
1281 from: &Path,
1282 to: &Path,
1283 options: CopyOptions,
1284 ) -> object_store::Result<()> {
1285 self.in_mem.copy_opts(from, to, options).await
1286 }
1287 }
1288
1289 struct MockSession {
1290 config: SessionConfig,
1291 runtime_env: Arc<RuntimeEnv>,
1292 }
1293
1294 impl MockSession {
1295 fn new() -> Self {
1296 Self {
1297 config: SessionConfig::new(),
1298 runtime_env: Arc::new(RuntimeEnv::default()),
1299 }
1300 }
1301
1302 fn with_runtime_env(runtime_env: Arc<RuntimeEnv>) -> Self {
1304 Self {
1305 config: SessionConfig::new(),
1306 runtime_env,
1307 }
1308 }
1309 }
1310
1311 #[async_trait::async_trait]
1312 impl Session for MockSession {
1313 fn session_id(&self) -> &str {
1314 unimplemented!()
1315 }
1316
1317 fn config(&self) -> &SessionConfig {
1318 &self.config
1319 }
1320
1321 fn catalog_list(&self) -> Arc<dyn CatalogProviderList> {
1322 Arc::new(EmptyCatalogProviderList)
1323 }
1324
1325 async fn create_physical_plan(
1326 &self,
1327 _logical_plan: &LogicalPlan,
1328 ) -> Result<Arc<dyn ExecutionPlan>> {
1329 unimplemented!()
1330 }
1331
1332 fn create_physical_expr(
1333 &self,
1334 _expr: Expr,
1335 _df_schema: &DFSchema,
1336 ) -> Result<Arc<dyn PhysicalExpr>> {
1337 unimplemented!()
1338 }
1339
1340 fn scalar_functions(&self) -> &HashMap<String, Arc<ScalarUDF>> {
1341 unimplemented!()
1342 }
1343
1344 fn higher_order_functions(&self) -> &HashMap<String, Arc<HigherOrderUDF>> {
1345 unimplemented!()
1346 }
1347
1348 fn aggregate_functions(&self) -> &HashMap<String, Arc<AggregateUDF>> {
1349 unimplemented!()
1350 }
1351
1352 fn window_functions(&self) -> &HashMap<String, Arc<WindowUDF>> {
1353 unimplemented!()
1354 }
1355
1356 fn extension_type_registry(&self) -> &ExtensionTypeRegistryRef {
1357 unimplemented!()
1358 }
1359
1360 fn runtime_env(&self) -> &Arc<RuntimeEnv> {
1361 &self.runtime_env
1362 }
1363
1364 fn execution_props(&self) -> &ExecutionProps {
1365 unimplemented!()
1366 }
1367
1368 fn as_any(&self) -> &dyn Any {
1369 unimplemented!()
1370 }
1371
1372 fn table_options(&self) -> &TableOptions {
1373 unimplemented!()
1374 }
1375
1376 fn table_options_mut(&mut self) -> &mut TableOptions {
1377 unimplemented!()
1378 }
1379
1380 fn task_ctx(&self) -> Arc<TaskContext> {
1381 unimplemented!()
1382 }
1383 }
1384}