Skip to main content

ursa_engine/database/
mod.rs

1//! The `.ursa` database file: a session's catalog, kept between processes.
2//!
3//! `ursa club.ursa` opens (or creates) a [`Database`] and installs it on the
4//! session. The design is the Tempra page `/sql/ursa-file.md` in
5//! `cl_dixon/ursa` (cldixon/ursa#237). On disk:
6//!
7//! ```text
8//! club.ursa          the catalog: the statements that defined each object
9//! club.ursa.d/       created on first use
10//!   lock             held while a process has the database open for writing
11//!   indexes/         stored graph indexes: `manifest.json` and `<hash>.idx`
12//! ```
13//!
14//! This module owns the file, the sidecar directory and the lock. It stores
15//! the catalog as an ordered list of statement texts ([`catalog_file`]) and
16//! knows nothing of SQL: which statement defines which object, and replaying
17//! them, is `ursa-sql`'s `database` module.
18//!
19//! A database is reached from the session config ([`database`],
20//! [`database_of_config`]), so any code holding the session state or a task
21//! context (the graph index cache, which stores indexes in it) can find it.
22//!
23//! **Relative paths** follow DuckDB. A relative file path in SQL (in `FROM`,
24//! a graph's edge or vertex table, an external table's `LOCATION`, a
25//! `COPY … TO` target) resolves against the current directory when the
26//! statement runs, with or without a database. When a definition is stored in
27//! the catalog, each of its local file paths is rewritten relative to the
28//! database's directory ([`Database::stored_location`]), or made absolute if
29//! it is outside that directory; replaying the catalog resolves the stored
30//! paths against the database's directory ([`Database::replayed_location`]).
31//! So a later process finds the same files from any directory, and a database
32//! and its data files can move together. URLs are never rewritten.
33
34use std::collections::BTreeMap;
35use std::fs::File;
36use std::io::{Read, Seek, Write};
37use std::path::{Component, Path, PathBuf};
38use std::sync::{Arc, Mutex, OnceLock};
39use std::time::{Duration, Instant};
40
41use datafusion::error::{DataFusionError, Result};
42use datafusion::execution::context::SessionState;
43use datafusion::prelude::SessionConfig;
44
45pub mod catalog_file;
46pub mod index_file;
47pub mod index_store;
48pub mod mapped;
49pub mod unavailable;
50
51pub use catalog_file::{CatalogFile, FORMAT, VERSION};
52pub use index_file::IndexKey;
53pub use index_store::IndexStore;
54pub use unavailable::{as_unavailable, check_available, UnavailableTable};
55
56/// How long a writer waits for another process to close the database.
57pub const DEFAULT_LOCK_TIMEOUT: Duration = Duration::from_secs(2);
58
59/// How to open a database.
60#[derive(Debug, Clone)]
61pub struct OpenOptions {
62    /// Open without the lock, and refuse statements that change the catalog.
63    /// The file must exist.
64    pub read_only: bool,
65    /// How long to wait for the lock before failing with "… is in use by
66    /// another process".
67    pub lock_timeout: Duration,
68}
69
70impl Default for OpenOptions {
71    fn default() -> Self {
72        Self {
73            read_only: false,
74            lock_timeout: DEFAULT_LOCK_TIMEOUT,
75        }
76    }
77}
78
79impl OpenOptions {
80    pub fn read_only() -> Self {
81        Self {
82            read_only: true,
83            ..Self::default()
84        }
85    }
86}
87
88/// An open `.ursa` database.
89#[derive(Debug)]
90pub struct Database {
91    /// The path as the user gave it: how messages name the database.
92    name: String,
93    /// The catalog file, absolute.
94    path: PathBuf,
95    /// The directory holding the catalog file, absolute: stored paths are
96    /// relative to it.
97    dir: PathBuf,
98    /// `club.ursa.d`, absolute.
99    sidecar: PathBuf,
100    read_only: bool,
101    /// The locked `club.ursa.d/lock`, held until the database is dropped.
102    /// `None` when read-only.
103    _lock: Option<File>,
104    /// The catalog (its statements, and any settings 0.8 or 0.9 saved), as
105    /// last read or written.
106    catalog: Mutex<CatalogFile>,
107    /// The stored graph indexes, opened on first use.
108    indexes: OnceLock<Arc<IndexStore>>,
109    /// The default `ursa.index_storage_limit`, worked out on first use.
110    default_limit: OnceLock<DefaultLimit>,
111}
112
113/// The setting that limits the bytes of stored indexes. Ursa 0.8 and 0.9
114/// saved it in a writable database's catalog (#327); since #353 it lasts for
115/// the session, and a saved value is no longer applied.
116pub const INDEX_STORAGE_LIMIT: &str = "ursa.index_storage_limit";
117
118/// A database's default `ursa.index_storage_limit`, and what it came from
119/// ([`crate::options::default_index_storage_limit`]).
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub struct DefaultLimit {
122    /// The limit.
123    pub bytes: u64,
124    /// The free space on the database's disk when it was worked out, if it
125    /// could be read.
126    pub free: Option<u64>,
127    /// The bytes of indexes the database stored then.
128    pub stored: u64,
129}
130
131impl Database {
132    /// Open the database at `path`, creating it (and its sidecar directory)
133    /// unless read-only. A writer takes the lock first, waiting up to
134    /// `options.lock_timeout`, then reads the catalog.
135    pub fn open(path: impl AsRef<Path>, options: &OpenOptions) -> Result<Self> {
136        let given = path.as_ref();
137        let name = given.display().to_string();
138        let path = std::path::absolute(given).map_err(|e| {
139            DataFusionError::Execution(format!("cannot open database '{name}': {e}"))
140        })?;
141        let dir = path
142            .parent()
143            .map(Path::to_path_buf)
144            .unwrap_or_else(|| PathBuf::from("/"));
145        let file_name = path.file_name().ok_or_else(|| {
146            DataFusionError::Execution(format!("'{name}' does not name a database file"))
147        })?;
148        let mut sidecar_name = file_name.to_os_string();
149        sidecar_name.push(".d");
150        let sidecar = dir.join(sidecar_name);
151
152        if options.read_only {
153            if !path.exists() {
154                return Err(DataFusionError::Execution(format!(
155                    "cannot open '{name}' read-only: the file does not exist"
156                )));
157            }
158            let catalog = CatalogFile::read(&path, &name)?;
159            return Ok(Self {
160                name,
161                path,
162                dir,
163                sidecar,
164                read_only: true,
165                _lock: None,
166                catalog: Mutex::new(catalog),
167                indexes: OnceLock::new(),
168                default_limit: OnceLock::new(),
169            });
170        }
171
172        if !dir.is_dir() {
173            return Err(DataFusionError::Execution(format!(
174                "cannot create database '{name}': the directory {} does not exist",
175                dir.display()
176            )));
177        }
178        let io = |what: &str, e: std::io::Error| {
179            DataFusionError::Execution(format!("cannot open database '{name}': {what}: {e}"))
180        };
181        std::fs::create_dir_all(&sidecar)
182            .map_err(|e| io(&format!("creating {}", sidecar.display()), e))?;
183        let mut lock = File::options()
184            .read(true)
185            .write(true)
186            .create(true)
187            .truncate(false)
188            .open(sidecar.join("lock"))
189            .map_err(|e| io("opening its lock file", e))?;
190        acquire(&lock, &name, options.lock_timeout)?;
191        record_holder(&mut lock);
192
193        let catalog = if path.exists() {
194            CatalogFile::read(&path, &name)?
195        } else {
196            let empty = CatalogFile::default();
197            empty.write(&path, &sidecar, &name)?;
198            empty
199        };
200        Ok(Self {
201            name,
202            path,
203            dir,
204            sidecar,
205            read_only: false,
206            _lock: Some(lock),
207            catalog: Mutex::new(catalog),
208            indexes: OnceLock::new(),
209            default_limit: OnceLock::new(),
210        })
211    }
212
213    /// The database as the user named it (`club.ursa`).
214    pub fn name(&self) -> &str {
215        &self.name
216    }
217
218    /// The catalog file, absolute.
219    pub fn path(&self) -> &Path {
220        &self.path
221    }
222
223    /// The directory holding the catalog file: stored relative paths are
224    /// relative to it.
225    pub fn dir(&self) -> &Path {
226        &self.dir
227    }
228
229    /// The sidecar directory, `club.ursa.d`. It exists unless read-only.
230    pub fn sidecar_dir(&self) -> &Path {
231        &self.sidecar
232    }
233
234    /// Where stored graph indexes go (`club.ursa.d/indexes`), created on
235    /// the first write.
236    pub fn index_dir(&self) -> PathBuf {
237        self.sidecar.join("indexes")
238    }
239
240    /// The database's stored graph indexes. A read-only database reads them
241    /// and never writes.
242    pub fn index_store(&self) -> Arc<IndexStore> {
243        Arc::clone(self.indexes.get_or_init(|| {
244            Arc::new(IndexStore::new(
245                self.index_dir(),
246                !self.read_only,
247                self.name.clone(),
248                self.default_index_storage_limit().bytes,
249            ))
250        }))
251    }
252
253    /// Wait for stored-index writes still running.
254    pub fn flush(&self) {
255        if let Some(store) = self.indexes.get() {
256            store.flush();
257        }
258    }
259
260    pub fn is_read_only(&self) -> bool {
261        self.read_only
262    }
263
264    fn catalog(&self) -> std::sync::MutexGuard<'_, CatalogFile> {
265        self.catalog.lock().unwrap_or_else(|e| e.into_inner())
266    }
267
268    /// The catalog's statements, in replay order.
269    pub fn statements(&self) -> Vec<String> {
270        self.catalog().statements.clone()
271    }
272
273    /// The settings Ursa 0.8 or 0.9 saved in the catalog, by full name, as
274    /// `SET` takes them. They are not applied (#353).
275    pub fn saved_settings(&self) -> BTreeMap<String, String> {
276        self.catalog().settings.clone()
277    }
278
279    /// Remove the settings 0.8 or 0.9 saved from the catalog, rewriting the
280    /// file if it has any. Refused when read-only.
281    pub fn remove_saved_settings(&self) -> Result<()> {
282        let mut catalog = self.catalog();
283        if catalog.settings.is_empty() {
284            return Ok(());
285        }
286        let updated = CatalogFile {
287            statements: catalog.statements.clone(),
288            settings: BTreeMap::new(),
289        };
290        self.write_catalog(&mut catalog, updated)
291    }
292
293    /// The default `ursa.index_storage_limit` of this database: 25% of the
294    /// free space on its disk plus the indexes it stores, within bounds
295    /// ([`crate::options::default_index_storage_limit`]). Worked out once,
296    /// when first needed, so it does not move while a session runs.
297    pub fn default_index_storage_limit(&self) -> DefaultLimit {
298        *self.default_limit.get_or_init(|| {
299            let on = if self.sidecar.is_dir() {
300                &self.sidecar
301            } else {
302                &self.dir
303            };
304            let free = free_space(on);
305            let stored = index_store::manifest_bytes(&self.index_dir());
306            DefaultLimit {
307                bytes: crate::options::default_index_storage_limit(
308                    free.map(|f| f.saturating_add(stored)),
309                ),
310                free,
311                stored,
312            }
313        })
314    }
315
316    /// The `ursa.index_storage_limit` in effect for the session `config`
317    /// belongs to: what it `SET`, or the database's default.
318    pub fn index_storage_limit(&self, config: &SessionConfig) -> u64 {
319        crate::options::index_storage_limit_set(config)
320            .unwrap_or_else(|| self.default_index_storage_limit().bytes)
321    }
322
323    /// Keep the stored indexes within the limit in effect for the session
324    /// `config` belongs to from now on: the next index stored makes room
325    /// within it. Nothing is removed now.
326    pub fn use_index_storage_limit(&self, config: &SessionConfig) {
327        let limit = self.index_storage_limit(config);
328        self.index_store().set_limit(limit);
329    }
330
331    /// Replace the catalog's statements with `statements`, rewriting the
332    /// file atomically (temporary file, `fsync`, rename). Refused when
333    /// read-only.
334    pub fn save(&self, statements: Vec<String>) -> Result<()> {
335        let mut catalog = self.catalog();
336        if !self.read_only && catalog.statements == statements {
337            return Ok(());
338        }
339        let updated = CatalogFile {
340            statements,
341            settings: catalog.settings.clone(),
342        };
343        self.write_catalog(&mut catalog, updated)
344    }
345
346    fn write_catalog(&self, current: &mut CatalogFile, updated: CatalogFile) -> Result<()> {
347        if self.read_only {
348            return Err(DataFusionError::Plan(format!(
349                "{} is open read-only",
350                self.name
351            )));
352        }
353        updated.write(&self.path, &self.sidecar, &self.name)?;
354        *current = updated;
355        Ok(())
356    }
357
358    /// How the catalog stores `location`, written in a statement run from
359    /// `cwd`: a local path inside the database's directory becomes relative to
360    /// it, any other local path becomes absolute. `None` when the location is
361    /// stored as written: a URL, a `~/…` path, or a path already in its
362    /// stored form.
363    pub fn stored_location(&self, location: &str, cwd: &Path) -> Option<String> {
364        if !is_local_path(location) {
365            return None;
366        }
367        let absolute = normalize(&cwd.join(location));
368        let canonical_dir = std::fs::canonicalize(&self.dir).ok();
369        let inside = [Some(&self.dir), canonical_dir.as_ref()]
370            .into_iter()
371            .flatten()
372            .find_map(|dir| absolute.strip_prefix(dir).ok());
373        let mut stored = match inside {
374            Some(relative) if relative.as_os_str().is_empty() => ".".to_string(),
375            Some(relative) => relative.to_string_lossy().into_owned(),
376            None => absolute.to_string_lossy().into_owned(),
377        };
378        keep_trailing_separator(location, &mut stored);
379        (stored != location).then_some(stored)
380    }
381
382    /// `location` from a stored statement as replay runs it: a relative local
383    /// path resolved against the database's directory; `None` for anything
384    /// else (a URL, an absolute path, `~/…`), which runs as stored.
385    pub fn replayed_location(&self, location: &str) -> Option<String> {
386        if !is_relative_path(location) {
387            return None;
388        }
389        let mut resolved = normalize(&self.dir.join(location))
390            .to_string_lossy()
391            .into_owned();
392        keep_trailing_separator(location, &mut resolved);
393        Some(resolved)
394    }
395}
396
397impl Drop for Database {
398    /// Finish writing stored indexes before the lock is released.
399    fn drop(&mut self) {
400        self.flush();
401    }
402}
403
404/// Whether `location` is a local path (not a URL, not starting with `~`).
405pub fn is_local_path(location: &str) -> bool {
406    if location.is_empty() || location.starts_with('~') {
407        return false;
408    }
409    match url::Url::parse(location) {
410        // A one-letter scheme is a Windows drive letter.
411        Ok(url) => url.scheme().len() == 1,
412        Err(_) => true,
413    }
414}
415
416/// Whether `location` is a relative local path (not a URL, not absolute, not
417/// starting with `~`).
418pub fn is_relative_path(location: &str) -> bool {
419    is_local_path(location) && Path::new(location).is_relative()
420}
421
422/// `path` with `.` and `..` components removed lexically, without touching
423/// the filesystem (the path may be a glob, or not exist yet).
424fn normalize(path: &Path) -> PathBuf {
425    let mut out = PathBuf::new();
426    for component in path.components() {
427        match component {
428            Component::CurDir => {}
429            Component::ParentDir => match out.components().next_back() {
430                Some(Component::Normal(_)) => {
431                    out.pop();
432                }
433                // `..` at the root stays at the root.
434                Some(Component::RootDir | Component::Prefix(_)) => {}
435                _ => out.push(".."),
436            },
437            other => out.push(other),
438        }
439    }
440    out
441}
442
443/// A directory written with a trailing separator (`data/`) keeps it.
444fn keep_trailing_separator(original: &str, rewritten: &mut String) {
445    let separator = std::path::MAIN_SEPARATOR;
446    if (original.ends_with('/') || original.ends_with(separator))
447        && !rewritten.ends_with(['/', separator])
448    {
449        rewritten.push(separator);
450    }
451}
452
453/// The bytes free to an unprivileged process on the file system holding
454/// `path`, if they can be read (on Unix; elsewhere `None`, and the default
455/// limit is its least, 4 GiB).
456fn free_space(path: &Path) -> Option<u64> {
457    #[cfg(unix)]
458    {
459        let stat = rustix::fs::statvfs(path).ok()?;
460        Some(stat.f_bavail.saturating_mul(stat.f_frsize))
461    }
462    #[cfg(not(unix))]
463    {
464        let _ = path;
465        None
466    }
467}
468
469/// Take the exclusive lock on `lock`, retrying until `timeout` has passed.
470fn acquire(lock: &File, name: &str, timeout: Duration) -> Result<()> {
471    let start = Instant::now();
472    loop {
473        match lock.try_lock() {
474            Ok(()) => return Ok(()),
475            Err(std::fs::TryLockError::WouldBlock) => {
476                if start.elapsed() >= timeout {
477                    let holder = holder(lock)
478                        .map(|pid| format!(" (process {pid})"))
479                        .unwrap_or_default();
480                    return Err(DataFusionError::Execution(format!(
481                        "{name} is in use by another process{holder}, which has it open for \
482                         writing; open it read-only to query it meanwhile (ursa --readonly \
483                         {name}), or wait for that process to finish"
484                    )));
485                }
486                std::thread::sleep(Duration::from_millis(50));
487            }
488            Err(std::fs::TryLockError::Error(e)) => {
489                return Err(DataFusionError::Execution(format!(
490                    "cannot lock database '{name}': {e}"
491                )))
492            }
493        }
494    }
495}
496
497/// Write this process's id into the lock file it holds, so another process
498/// waiting for the lock can name it. Best effort.
499fn record_holder(lock: &mut File) {
500    let _ = lock.set_len(0).and_then(|()| {
501        lock.rewind()?;
502        writeln!(lock, "{}", std::process::id())?;
503        lock.flush()
504    });
505}
506
507/// The id of the process holding `lock`, as it recorded it, if it can be read.
508fn holder(lock: &File) -> Option<u32> {
509    let mut text = String::new();
510    let mut reader = lock;
511    reader.rewind().ok()?;
512    reader.take(32).read_to_string(&mut text).ok()?;
513    text.trim().parse().ok()
514}
515
516/// Where a session keeps its database: empty for an in-memory session, set
517/// once by opening or attaching one. Installed on every session's config by
518/// `new_session`, so `ATTACH` can fill it later.
519#[derive(Debug, Default)]
520pub struct DatabaseSlot {
521    database: OnceLock<Arc<Database>>,
522}
523
524impl DatabaseSlot {
525    pub fn get(&self) -> Option<Arc<Database>> {
526        self.database.get().cloned()
527    }
528
529    /// Put `database` in the slot; fails if the session already has one.
530    pub fn set(&self, database: Arc<Database>) -> Result<()> {
531        self.database
532            .set(database)
533            .map_err(|_| DataFusionError::Plan("this session already has a database open".into()))
534    }
535}
536
537/// Install an empty database slot on `config` (done by `new_session`).
538pub(crate) fn with_database_slot(config: SessionConfig) -> SessionConfig {
539    config.with_extension(Arc::new(DatabaseSlot::default()))
540}
541
542/// The session's database slot.
543pub fn slot(state: &SessionState) -> Arc<DatabaseSlot> {
544    slot_of_config(state.config())
545}
546
547fn slot_of_config(config: &SessionConfig) -> Arc<DatabaseSlot> {
548    config
549        .get_extension::<DatabaseSlot>()
550        .expect("an Ursa session has a database slot (built by ursa_engine::new_session)")
551}
552
553/// The session's database, if it has one.
554pub fn database(state: &SessionState) -> Option<Arc<Database>> {
555    database_of_config(state.config())
556}
557
558/// The database of the session `config` belongs to, if it has one. A task
559/// context's `session_config()` reaches it too.
560pub fn database_of_config(config: &SessionConfig) -> Option<Arc<Database>> {
561    config.get_extension::<DatabaseSlot>()?.get()
562}
563
564/// Wait for the session's stored-index writes, if it has a database. Call it
565/// before a process exits, so an index built by its last query is stored.
566pub fn flush(state: &SessionState) {
567    if let Some(db) = database(state) {
568        db.flush();
569    }
570}
571
572#[cfg(test)]
573mod tests;