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