Skip to main content

ursa_engine/
lib.rs

1//! Ursa's SQL engine session.
2//!
3//! [`new_session`] builds a DataFusion [`SessionContext`] on which a file is a
4//! table: `SELECT * FROM 'edges.parquet'`, `'edges.csv.gz'`, `'edges/'`,
5//! `'edges/*.parquet'`, `'events.jsonl'`, and the same over `s3://`, `gs://`,
6//! `az://` and `https://`, with object stores registered the first time a URL
7//! is read. `read_parquet`, `read_csv` and `read_json` read the same with
8//! options ([`read_functions`]).
9//!
10//! Graphs are defined per session ([`graph`]). A session may have a `.ursa`
11//! database ([`database`]), which keeps its catalog between processes.
12
13use std::sync::Arc;
14
15use datafusion::catalog::DynamicFileCatalog;
16use datafusion::prelude::{SessionConfig, SessionContext};
17
18mod blocking;
19pub mod database;
20mod duckdb_functions;
21pub mod error;
22mod file_table;
23pub mod graph;
24pub mod notices;
25pub mod options;
26pub mod paths;
27pub mod read_functions;
28pub mod serial;
29pub mod session_files;
30pub mod stores;
31
32pub use blocking::{run_blocking, BlockingError};
33pub use error::user_message;
34pub use file_table::{open_file_table, open_files, FileFormat, FileOptions};
35pub use stores::{ensure_object_store, ensure_object_store_for};
36
37/// A session with Ursa's defaults.
38///
39/// Unlike DataFusion's default, a Parquet file's schema metadata is kept when
40/// it is read (`datafusion.execution.parquet.skip_metadata = false`), so the
41/// `ursa.*` column roles a result was written with (#431) come back with it,
42/// as they do from an Arrow file. `SET datafusion.execution.parquet.skip_metadata = true`
43/// drops them again.
44pub fn new_session() -> SessionContext {
45    let mut config = SessionConfig::new();
46    config.options_mut().execution.parquet.skip_metadata = false;
47    new_session_with_config(config)
48}
49
50/// A session with Ursa's file tables over `config`. `information_schema` is
51/// turned on, so `SHOW TABLES` and `SHOW COLUMNS` work.
52///
53/// In the browser (wasm32) the session plans for one partition. DataFusion runs
54/// each extra partition as a spawned Tokio task, and the browser build has no
55/// runtime to spawn on; its futures are driven from JavaScript's event loop, as
56/// in DataFusion's own `wasmtest` crate (#278).
57pub fn new_session_with_config(config: SessionConfig) -> SessionContext {
58    #[cfg(target_arch = "wasm32")]
59    let config = config.with_target_partitions(1);
60    let config = graph::with_algorithms(graph::with_registry(config.with_information_schema(true)));
61    let config = database::with_database_slot(options::with_options(config));
62    let config = notices::with_notice_slot(config);
63    let config = read_functions::with_read_tables(config);
64    let ctx = SessionContext::new_with_config(config);
65    // Graph schemas are added to and dropped from the unwrapped catalogs.
66    graph::registry_of(&ctx).set_catalogs(Arc::clone(ctx.state().catalog_list()));
67    // As `SessionContext::enable_url_table` does, with Ursa's factory in place
68    // of DataFusion's.
69    let factory = Arc::new(file_table::FileTableFactory::default());
70    let catalogs = Arc::new(DynamicFileCatalog::new(
71        Arc::clone(ctx.state().catalog_list()),
72        Arc::clone(&factory) as _,
73    ));
74    let session_id = ctx.session_id();
75    let ctx = ctx
76        .into_state_builder()
77        .with_session_id(session_id)
78        .with_catalog_list(catalogs)
79        .with_query_planner(graph::query_planner())
80        .with_physical_optimizer_rule(graph::edge_order_rule());
81    // In the browser, after the graph rules: every plan runs on the task
82    // that polls it.
83    #[cfg(target_arch = "wasm32")]
84    let ctx = ctx.with_physical_optimizer_rule(Arc::new(serial::SingleTask));
85    // Last of all: hide the inputs a path search over a held index skips.
86    let ctx = ctx.with_physical_optimizer_rule(graph::collapse_held_rule());
87    let mut state = ctx.build();
88    // Parquet files have their footers checked before the parquet crate
89    // reads them: a truncated or fake file is an error, not a panic (#332).
90    state
91        .register_file_format(
92            Arc::new(ursa_io::parquet_footer::ValidParquetFactory::new()),
93            true,
94        )
95        .expect("registering a file format cannot fail");
96    // ... and an empty one is an error, not zero rows: DataFusion's listing
97    // skips a 0-byte file before the format sees it.
98    if let Some(parquet) = state.table_factories_mut().get_mut("PARQUET") {
99        *parquet = Arc::new(file_table::CheckedParquetTables(Arc::clone(parquet)));
100    }
101    for ext in ["jsonl", "ndjson"] {
102        state
103            .register_file_format(Arc::new(file_table::JsonLines(ext)), false)
104            .expect("registering a file format cannot fail");
105    }
106    let ctx: SessionContext = state.into();
107    graph::register_functions(&ctx).expect("registering a relation planner cannot fail");
108    // DuckDB's names for DataFusion's functions: list_value, strftime, … (#417).
109    duckdb_functions::register(&ctx);
110    let reads = read_functions::ReadFunctions::new(ctx.state().config())
111        .expect("the session config has a place for read_* tables");
112    ctx.register_relation_planner(Arc::new(reads))
113        .expect("registering a relation planner cannot fail");
114    factory.attach(ctx.state_weak_ref());
115    ctx
116}