Skip to main content

ursa_engine/
file_table.rs

1//! Files as tables: the `UrlTableFactory` behind `SELECT * FROM 'file.parquet'`.
2//!
3//! This does what DataFusion's `DynamicListTableFactory` (installed by
4//! `SessionContext::enable_url_table`) does, plus four things it does not:
5//!
6//! - registers the object store for a URL the first time it is read (as
7//!   datafusion-cli's `DynamicObjectStoreCatalog` does);
8//! - expands globs in URLs, not just in local paths (see [`crate::paths`]);
9//! - reads `.jsonl` and `.ndjson` files (and `.jsonl.gz`, …) as
10//!   newline-delimited JSON, as DataFusion reads `.json`;
11//! - reports why a location could not be opened. DataFusion's factory turns any
12//!   failure into "table not found", which hides a missing file or an unknown
13//!   extension.
14//!
15//! [`open_files`] is the same with options: what `read_csv(...)` and its
16//! siblings plan (see [`crate::read_functions`]).
17
18use 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/// Opens a location named in `FROM` as a listing table.
40#[derive(Debug, Default)]
41pub(crate) struct FileTableFactory {
42    /// The session this factory belongs to, set once the session is built.
43    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
68/// Open `location` (a path, glob, directory or URL) as a listing table. The
69/// format and compression come from the file extension; Hive-style partition
70/// directories (`year=2024/`) become columns. A relative path is relative to
71/// the session's root ([`crate::paths::Root`]), or with none to the current
72/// directory, in a session with a database too: a stored
73/// definition's paths are made relative to the database's directory when it is
74/// stored, and resolved against it on replay (see [`crate::database`]).
75pub 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/// A file format Ursa reads.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum FileFormat {
85    Parquet,
86    Csv,
87    /// Newline-delimited JSON, or a JSON array of objects with
88    /// [`FileOptions::newline_delimited`] `false`.
89    Json,
90    Arrow,
91}
92
93impl FileFormat {
94    /// The format a file extension names (without its dot or compression
95    /// suffix). `json`, `jsonl` and `ndjson` are all newline-delimited JSON.
96    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    /// The extension DataFusion registers the format's factory under.
107    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    /// Whether the format's files are compressed whole (`.csv.gz`).
117    fn compressible(self) -> bool {
118        matches!(self, Self::Csv | Self::Json)
119    }
120}
121
122/// How to read files, beyond what their extension says: the options of
123/// `read_csv(...)` and its siblings. `None` leaves a choice to the extension
124/// or to the session's defaults.
125#[derive(Debug, Clone, Default, PartialEq, Eq)]
126pub struct FileOptions {
127    /// The format, whatever the extension.
128    pub format: Option<FileFormat>,
129    /// The compression of CSV or JSON files, whatever the extension.
130    pub compression: Option<CompressionTypeVariant>,
131    /// CSV: whether the first line is a header.
132    pub has_header: Option<bool>,
133    /// CSV: the field delimiter.
134    pub delimiter: Option<u8>,
135    /// CSV: the quote character.
136    pub quote: Option<u8>,
137    /// JSON: one object per line (`true`), or one array of objects (`false`).
138    pub newline_delimited: Option<bool>,
139}
140
141/// Open `locations` (paths, globs, directories or URLs) as one listing table,
142/// read as `options` say. What `options` leaves open comes from the extension
143/// of the first file found, as DataFusion infers it; a directory or glob
144/// lists only the files with that extension. Each location must name a file.
145pub 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    // Each location's first file's extensions (`.jsonl.gz`), to list by.
154    let mut extensions = Vec::with_capacity(locations.len());
155    for location in locations {
156        // A file the session keeps under this name (#517) is the one read.
157        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        // A directory or glob lists the files with the first file's extension
174        // and compression suffix, as DataFusion's `infer_options` does; a file
175        // whose extension names no format (`read_csv('data.txt')`) by its own.
176        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    // One listing extension for all the locations: theirs if they agree
232    // (`['a.jsonl', 'b.ndjson']` do not), else none.
233    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    // An empty Parquet file is an error naming it, not zero rows.
248    ursa_io::parquet_footer::check_listed_files(state, &table).await?;
249    Ok(Arc::new(table))
250}
251
252/// `CREATE EXTERNAL TABLE … STORED AS PARQUET`: DataFusion's table factory,
253/// with an empty file in the table's locations an error naming it, not zero
254/// rows (see [`ursa_io::parquet_footer::check_listed_files`]).
255#[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/// JSON under another extension, for DataFusion's own lookups of a format by
274/// extension: `COPY … TO 'out.jsonl'` writes newline-delimited JSON, as `COPY
275/// … TO 'out.json'` does.
276#[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
299/// A file's extension and compression suffix, as DataFusion infers them
300/// (`x.jsonl.gz` has `jsonl` and `gz`); no extension for a file without one.
301fn extensions_of(path: &str) -> Result<(Option<String>, Option<String>)> {
302    let (ext, suffix) = ListingTableConfig::infer_file_extension_and_compression_type(path)?;
303    // For a file without an extension, DataFusion gives the whole path.
304    let ext = (!ext.contains('/') && ext != path).then_some(ext);
305    Ok((ext, suffix))
306}
307
308/// The value DataFusion's `format.compression` option takes for `c`.
309fn compression_name(c: CompressionTypeVariant) -> String {
310    match c {
311        CompressionTypeVariant::UNCOMPRESSED => "uncompressed".to_string(),
312        other => other.to_string().to_lowercase(),
313    }
314}
315
316/// Say why `location` could not be opened, naming the path once: an error
317/// that already names the file it could not read (a bad CSV file, perhaps
318/// one of a glob's) says enough as it is (N40).
319fn 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}