1use std::collections::HashMap;
19use std::sync::{Arc, OnceLock, Weak};
20
21use async_trait::async_trait;
22use datafusion::catalog::Session;
23use datafusion::catalog::{TableProvider, TableProviderFactory, UrlTableFactory};
24use datafusion::common::parsers::CompressionTypeVariant;
25use datafusion::common::GetExt;
26use datafusion::datasource::file_format::json::JsonFormatFactory;
27use datafusion::datasource::file_format::{FileFormat as DataFusionFileFormat, FileFormatFactory};
28use datafusion::datasource::listing::{ListingOptions, ListingTable, ListingTableConfig};
29use datafusion::error::{DataFusionError, Result};
30use datafusion::execution::context::SessionState;
31use datafusion::logical_expr::CreateExternalTable;
32use futures::StreamExt;
33use parking_lot::RwLock;
34
35use crate::error::user_message;
36use crate::paths::{looks_like_location, session_table_url};
37use crate::stores::ensure_object_store;
38
39#[derive(Debug, Default)]
41pub(crate) struct FileTableFactory {
42 session: OnceLock<Weak<RwLock<SessionState>>>,
44}
45
46impl FileTableFactory {
47 pub(crate) fn attach(&self, session: Weak<RwLock<SessionState>>) {
48 let _ = self.session.set(session);
49 }
50}
51
52#[async_trait]
53impl UrlTableFactory for FileTableFactory {
54 async fn try_new(&self, name: &str) -> Result<Option<Arc<dyn TableProvider>>> {
55 if !looks_like_location(name) {
56 return Ok(None);
57 }
58 let state = self
59 .session
60 .get()
61 .and_then(Weak::upgrade)
62 .map(|state| state.read().clone())
63 .ok_or_else(|| DataFusionError::Internal("the session has been dropped".into()))?;
64 open_file_table(&state, name).await.map(Some)
65 }
66}
67
68pub async fn open_file_table(
76 state: &SessionState,
77 location: &str,
78) -> Result<Arc<dyn TableProvider>> {
79 open_files(state, &[location.to_string()], &FileOptions::default()).await
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum FileFormat {
85 Parquet,
86 Csv,
87 Json,
90 Arrow,
91}
92
93impl FileFormat {
94 pub fn from_extension(ext: &str) -> Option<Self> {
97 match ext.to_ascii_lowercase().as_str() {
98 "parquet" => Some(Self::Parquet),
99 "csv" => Some(Self::Csv),
100 "json" | "jsonl" | "ndjson" => Some(Self::Json),
101 "arrow" => Some(Self::Arrow),
102 _ => None,
103 }
104 }
105
106 fn factory(self) -> &'static str {
108 match self {
109 Self::Parquet => "parquet",
110 Self::Csv => "csv",
111 Self::Json => "json",
112 Self::Arrow => "arrow",
113 }
114 }
115
116 fn compressible(self) -> bool {
118 matches!(self, Self::Csv | Self::Json)
119 }
120}
121
122#[derive(Debug, Clone, Default, PartialEq, Eq)]
126pub struct FileOptions {
127 pub format: Option<FileFormat>,
129 pub compression: Option<CompressionTypeVariant>,
131 pub has_header: Option<bool>,
133 pub delimiter: Option<u8>,
135 pub quote: Option<u8>,
137 pub newline_delimited: Option<bool>,
139}
140
141pub async fn open_files(
146 state: &SessionState,
147 locations: &[String],
148 options: &FileOptions,
149) -> Result<Arc<dyn TableProvider>> {
150 let shown = locations.join("', '");
151 let mut urls = Vec::with_capacity(locations.len());
152 let mut first_file = None;
153 let mut extensions = Vec::with_capacity(locations.len());
155 for location in locations {
156 let url = match crate::session_files::existing(state.runtime_env(), location).await {
158 Some(kept) => session_table_url(state.config(), &kept)?,
159 None => session_table_url(state.config(), location)?,
160 };
161 ensure_object_store(state.runtime_env(), url.get_url()).await?;
162 let store = state.runtime_env().object_store(&url)?;
163 let file = url
164 .list_all_files(state, store.as_ref(), "")
165 .await
166 .map_err(|e| explain(location, &e))?
167 .next()
168 .await
169 .transpose()
170 .map_err(|e| explain(location, &e))?
171 .ok_or_else(|| DataFusionError::Plan(format!("no file found at '{location}'")))?;
172 let (ext, suffix) = extensions_of(file.location.as_ref())?;
173 extensions.push(match (&ext, &suffix) {
177 (Some(ext), Some(suffix)) => format!(".{ext}.{suffix}"),
178 (Some(ext), None) => format!(".{ext}"),
179 (None, _) => String::new(),
180 });
181 first_file.get_or_insert((ext, suffix));
182 urls.push(url);
183 }
184 let (ext, suffix) =
185 first_file.ok_or_else(|| DataFusionError::Plan("no file to read".into()))?;
186 let named = ext.as_deref().and_then(FileFormat::from_extension);
187 let format = options.format.or(named).ok_or_else(|| {
188 DataFusionError::Plan(format!(
189 "cannot tell the format of '{shown}' from its extension; Ursa reads .parquet, \
190 .csv, .json, .jsonl, .ndjson and .arrow files, and compressed CSV and JSON (.gz, \
191 .bz2, .xz, .zst). read_parquet(), read_csv() and read_json() read a file \
192 whatever its extension"
193 ))
194 })?;
195 let mut format_options = HashMap::new();
196 let mut set = |key: &str, value: String| {
197 format_options.insert(format!("format.{key}"), value);
198 };
199 if format.compressible() {
200 let compression = match (options.compression, &suffix) {
201 (Some(c), _) => Some(c),
202 (None, Some(s)) => Some(s.parse::<CompressionTypeVariant>()?),
203 (None, None) => None,
204 };
205 if let Some(c) = compression {
206 set("compression", compression_name(c));
207 }
208 }
209 if format == FileFormat::Csv {
210 if let Some(header) = options.has_header {
211 set("has_header", header.to_string());
212 }
213 if let Some(delimiter) = options.delimiter {
214 set("delimiter", char::from(delimiter).to_string());
215 }
216 if let Some(quote) = options.quote {
217 set("quote", char::from(quote).to_string());
218 }
219 }
220 if format == FileFormat::Json {
221 if let Some(newline_delimited) = options.newline_delimited {
222 set("newline_delimited", newline_delimited.to_string());
223 }
224 }
225 let file_format = state
226 .get_file_format_factory(format.factory())
227 .ok_or_else(|| {
228 DataFusionError::Internal(format!("no {} file format factory", format.factory()))
229 })?
230 .create(state, &format_options)?;
231 let extension = if extensions.windows(2).all(|w| w[0] == w[1]) {
234 extensions.swap_remove(0)
235 } else {
236 String::new()
237 };
238 let config = ListingTableConfig::new_with_multi_paths(urls)
239 .with_listing_options(ListingOptions::new(file_format).with_file_extension(extension))
240 .infer_partitions_from_path(state)
241 .await
242 .map_err(|e| explain(&shown, &e))?
243 .infer_schema(state)
244 .await
245 .map_err(|e| explain(&shown, &e))?;
246 let table = ListingTable::try_new(config)?;
247 ursa_io::parquet_footer::check_listed_files(state, &table).await?;
249 Ok(Arc::new(table))
250}
251
252#[derive(Debug)]
256pub(crate) struct CheckedParquetTables(pub(crate) Arc<dyn TableProviderFactory>);
257
258#[async_trait]
259impl TableProviderFactory for CheckedParquetTables {
260 async fn create(
261 &self,
262 state: &dyn Session,
263 cmd: &CreateExternalTable,
264 ) -> Result<Arc<dyn TableProvider>> {
265 let table = self.0.create(state, cmd).await?;
266 if let Some(listing) = table.downcast_ref::<ListingTable>() {
267 ursa_io::parquet_footer::check_listed_files(state, listing).await?;
268 }
269 Ok(table)
270 }
271}
272
273#[derive(Debug)]
277pub(crate) struct JsonLines(pub(crate) &'static str);
278
279impl FileFormatFactory for JsonLines {
280 fn create(
281 &self,
282 state: &dyn Session,
283 format_options: &HashMap<String, String>,
284 ) -> Result<Arc<dyn DataFusionFileFormat>> {
285 JsonFormatFactory::new().create(state, format_options)
286 }
287
288 fn default(&self) -> Arc<dyn DataFusionFileFormat> {
289 JsonFormatFactory::new().default()
290 }
291}
292
293impl GetExt for JsonLines {
294 fn get_ext(&self) -> String {
295 self.0.to_string()
296 }
297}
298
299fn extensions_of(path: &str) -> Result<(Option<String>, Option<String>)> {
302 let (ext, suffix) = ListingTableConfig::infer_file_extension_and_compression_type(path)?;
303 let ext = (!ext.contains('/') && ext != path).then_some(ext);
305 Ok((ext, suffix))
306}
307
308fn compression_name(c: CompressionTypeVariant) -> String {
310 match c {
311 CompressionTypeVariant::UNCOMPRESSED => "uncompressed".to_string(),
312 other => other.to_string().to_lowercase(),
313 }
314}
315
316fn explain(location: &str, err: &DataFusionError) -> DataFusionError {
320 let message = user_message(err);
321 if message.starts_with("cannot read '") {
322 DataFusionError::Plan(message)
323 } else {
324 DataFusionError::Plan(format!("cannot read '{location}': {message}"))
325 }
326}