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