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, 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(
75 state: &SessionState,
76 location: &str,
77) -> Result<Arc<dyn TableProvider>> {
78 open_files(state, &[location.to_string()], &FileOptions::default()).await
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum FileFormat {
84 Parquet,
85 Csv,
86 Json,
89 Arrow,
90}
91
92impl FileFormat {
93 pub fn from_extension(ext: &str) -> Option<Self> {
96 match ext.to_ascii_lowercase().as_str() {
97 "parquet" => Some(Self::Parquet),
98 "csv" => Some(Self::Csv),
99 "json" | "jsonl" | "ndjson" => Some(Self::Json),
100 "arrow" => Some(Self::Arrow),
101 _ => None,
102 }
103 }
104
105 fn factory(self) -> &'static str {
107 match self {
108 Self::Parquet => "parquet",
109 Self::Csv => "csv",
110 Self::Json => "json",
111 Self::Arrow => "arrow",
112 }
113 }
114
115 fn compressible(self) -> bool {
117 matches!(self, Self::Csv | Self::Json)
118 }
119}
120
121#[derive(Debug, Clone, Default, PartialEq, Eq)]
125pub struct FileOptions {
126 pub format: Option<FileFormat>,
128 pub compression: Option<CompressionTypeVariant>,
130 pub has_header: Option<bool>,
132 pub delimiter: Option<u8>,
134 pub quote: Option<u8>,
136 pub newline_delimited: Option<bool>,
138}
139
140pub async fn open_files(
145 state: &SessionState,
146 locations: &[String],
147 options: &FileOptions,
148) -> Result<Arc<dyn TableProvider>> {
149 let shown = locations.join("', '");
150 let mut urls = Vec::with_capacity(locations.len());
151 let mut first_file = None;
152 let mut extensions = Vec::with_capacity(locations.len());
154 for location in locations {
155 let url = table_url(location)?;
156 ensure_object_store(state.runtime_env(), url.get_url()).await?;
157 let store = state.runtime_env().object_store(&url)?;
158 let file = url
159 .list_all_files(state, store.as_ref(), "")
160 .await
161 .map_err(|e| explain(location, &e))?
162 .next()
163 .await
164 .transpose()
165 .map_err(|e| explain(location, &e))?
166 .ok_or_else(|| DataFusionError::Plan(format!("no file found at '{location}'")))?;
167 let (ext, suffix) = extensions_of(file.location.as_ref())?;
168 extensions.push(match (&ext, &suffix) {
172 (Some(ext), Some(suffix)) => format!(".{ext}.{suffix}"),
173 (Some(ext), None) => format!(".{ext}"),
174 (None, _) => String::new(),
175 });
176 first_file.get_or_insert((ext, suffix));
177 urls.push(url);
178 }
179 let (ext, suffix) =
180 first_file.ok_or_else(|| DataFusionError::Plan("no file to read".into()))?;
181 let named = ext.as_deref().and_then(FileFormat::from_extension);
182 let format = options.format.or(named).ok_or_else(|| {
183 DataFusionError::Plan(format!(
184 "cannot tell the format of '{shown}' from its extension; Ursa reads .parquet, \
185 .csv, .json, .jsonl, .ndjson and .arrow files, and compressed CSV and JSON (.gz, \
186 .bz2, .xz, .zst). read_parquet(), read_csv() and read_json() read a file \
187 whatever its extension"
188 ))
189 })?;
190 let mut format_options = HashMap::new();
191 let mut set = |key: &str, value: String| {
192 format_options.insert(format!("format.{key}"), value);
193 };
194 if format.compressible() {
195 let compression = match (options.compression, &suffix) {
196 (Some(c), _) => Some(c),
197 (None, Some(s)) => Some(s.parse::<CompressionTypeVariant>()?),
198 (None, None) => None,
199 };
200 if let Some(c) = compression {
201 set("compression", compression_name(c));
202 }
203 }
204 if format == FileFormat::Csv {
205 if let Some(header) = options.has_header {
206 set("has_header", header.to_string());
207 }
208 if let Some(delimiter) = options.delimiter {
209 set("delimiter", char::from(delimiter).to_string());
210 }
211 if let Some(quote) = options.quote {
212 set("quote", char::from(quote).to_string());
213 }
214 }
215 if format == FileFormat::Json {
216 if let Some(newline_delimited) = options.newline_delimited {
217 set("newline_delimited", newline_delimited.to_string());
218 }
219 }
220 let file_format = state
221 .get_file_format_factory(format.factory())
222 .ok_or_else(|| {
223 DataFusionError::Internal(format!("no {} file format factory", format.factory()))
224 })?
225 .create(state, &format_options)?;
226 let extension = if extensions.windows(2).all(|w| w[0] == w[1]) {
229 extensions.swap_remove(0)
230 } else {
231 String::new()
232 };
233 let config = ListingTableConfig::new_with_multi_paths(urls)
234 .with_listing_options(ListingOptions::new(file_format).with_file_extension(extension))
235 .infer_partitions_from_path(state)
236 .await
237 .map_err(|e| explain(&shown, &e))?
238 .infer_schema(state)
239 .await
240 .map_err(|e| explain(&shown, &e))?;
241 let table = ListingTable::try_new(config)?;
242 ursa_io::parquet_footer::check_listed_files(state, &table).await?;
244 Ok(Arc::new(table))
245}
246
247#[derive(Debug)]
251pub(crate) struct CheckedParquetTables(pub(crate) Arc<dyn TableProviderFactory>);
252
253#[async_trait]
254impl TableProviderFactory for CheckedParquetTables {
255 async fn create(
256 &self,
257 state: &dyn Session,
258 cmd: &CreateExternalTable,
259 ) -> Result<Arc<dyn TableProvider>> {
260 let table = self.0.create(state, cmd).await?;
261 if let Some(listing) = table.downcast_ref::<ListingTable>() {
262 ursa_io::parquet_footer::check_listed_files(state, listing).await?;
263 }
264 Ok(table)
265 }
266}
267
268#[derive(Debug)]
272pub(crate) struct JsonLines(pub(crate) &'static str);
273
274impl FileFormatFactory for JsonLines {
275 fn create(
276 &self,
277 state: &dyn Session,
278 format_options: &HashMap<String, String>,
279 ) -> Result<Arc<dyn DataFusionFileFormat>> {
280 JsonFormatFactory::new().create(state, format_options)
281 }
282
283 fn default(&self) -> Arc<dyn DataFusionFileFormat> {
284 JsonFormatFactory::new().default()
285 }
286}
287
288impl GetExt for JsonLines {
289 fn get_ext(&self) -> String {
290 self.0.to_string()
291 }
292}
293
294fn extensions_of(path: &str) -> Result<(Option<String>, Option<String>)> {
297 let (ext, suffix) = ListingTableConfig::infer_file_extension_and_compression_type(path)?;
298 let ext = (!ext.contains('/') && ext != path).then_some(ext);
300 Ok((ext, suffix))
301}
302
303fn compression_name(c: CompressionTypeVariant) -> String {
305 match c {
306 CompressionTypeVariant::UNCOMPRESSED => "uncompressed".to_string(),
307 other => other.to_string().to_lowercase(),
308 }
309}
310
311fn explain(location: &str, err: &DataFusionError) -> DataFusionError {
315 let message = user_message(err);
316 if message.starts_with("cannot read '") {
317 DataFusionError::Plan(message)
318 } else {
319 DataFusionError::Plan(format!("cannot read '{location}': {message}"))
320 }
321}