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, 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 current directory, in a session with a database too: a stored
72/// definition's paths are made relative to the database's directory when it is
73/// stored, and resolved against it on replay (see [`crate::database`]).
74pub 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/// A file format Ursa reads.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum FileFormat {
84    Parquet,
85    Csv,
86    /// Newline-delimited JSON, or a JSON array of objects with
87    /// [`FileOptions::newline_delimited`] `false`.
88    Json,
89    Arrow,
90}
91
92impl FileFormat {
93    /// The format a file extension names (without its dot or compression
94    /// suffix). `json`, `jsonl` and `ndjson` are all newline-delimited JSON.
95    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    /// The extension DataFusion registers the format's factory under.
106    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    /// Whether the format's files are compressed whole (`.csv.gz`).
116    fn compressible(self) -> bool {
117        matches!(self, Self::Csv | Self::Json)
118    }
119}
120
121/// How to read files, beyond what their extension says: the options of
122/// `read_csv(...)` and its siblings. `None` leaves a choice to the extension
123/// or to the session's defaults.
124#[derive(Debug, Clone, Default, PartialEq, Eq)]
125pub struct FileOptions {
126    /// The format, whatever the extension.
127    pub format: Option<FileFormat>,
128    /// The compression of CSV or JSON files, whatever the extension.
129    pub compression: Option<CompressionTypeVariant>,
130    /// CSV: whether the first line is a header.
131    pub has_header: Option<bool>,
132    /// CSV: the field delimiter.
133    pub delimiter: Option<u8>,
134    /// CSV: the quote character.
135    pub quote: Option<u8>,
136    /// JSON: one object per line (`true`), or one array of objects (`false`).
137    pub newline_delimited: Option<bool>,
138}
139
140/// Open `locations` (paths, globs, directories or URLs) as one listing table,
141/// read as `options` say. What `options` leaves open comes from the extension
142/// of the first file found, as DataFusion infers it; a directory or glob
143/// lists only the files with that extension. Each location must name a file.
144pub 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    // Each location's first file's extensions (`.jsonl.gz`), to list by.
153    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        // A directory or glob lists the files with the first file's extension
169        // and compression suffix, as DataFusion's `infer_options` does; a file
170        // whose extension names no format (`read_csv('data.txt')`) by its own.
171        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    // One listing extension for all the locations: theirs if they agree
227    // (`['a.jsonl', 'b.ndjson']` do not), else none.
228    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    // An empty Parquet file is an error naming it, not zero rows.
243    ursa_io::parquet_footer::check_listed_files(state, &table).await?;
244    Ok(Arc::new(table))
245}
246
247/// `CREATE EXTERNAL TABLE … STORED AS PARQUET`: DataFusion's table factory,
248/// with an empty file in the table's locations an error naming it, not zero
249/// rows (see [`ursa_io::parquet_footer::check_listed_files`]).
250#[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/// JSON under another extension, for DataFusion's own lookups of a format by
269/// extension: `COPY … TO 'out.jsonl'` writes newline-delimited JSON, as `COPY
270/// … TO 'out.json'` does.
271#[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
294/// A file's extension and compression suffix, as DataFusion infers them
295/// (`x.jsonl.gz` has `jsonl` and `gz`); no extension for a file without one.
296fn extensions_of(path: &str) -> Result<(Option<String>, Option<String>)> {
297    let (ext, suffix) = ListingTableConfig::infer_file_extension_and_compression_type(path)?;
298    // For a file without an extension, DataFusion gives the whole path.
299    let ext = (!ext.contains('/') && ext != path).then_some(ext);
300    Ok((ext, suffix))
301}
302
303/// The value DataFusion's `format.compression` option takes for `c`.
304fn compression_name(c: CompressionTypeVariant) -> String {
305    match c {
306        CompressionTypeVariant::UNCOMPRESSED => "uncompressed".to_string(),
307        other => other.to_string().to_lowercase(),
308    }
309}
310
311/// Say why `location` could not be opened, naming the path once: an error
312/// that already names the file it could not read (a bad CSV file, perhaps
313/// one of a glob's) says enough as it is (N40).
314fn 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}