1use 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
53pub const DEFAULT_LOCK_TIMEOUT: Duration = Duration::from_secs(2);
55
56#[derive(Debug, Clone)]
58pub struct OpenOptions {
59 pub read_only: bool,
62 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#[derive(Debug)]
87pub struct Database {
88 name: String,
90 path: PathBuf,
92 dir: PathBuf,
95 sidecar: PathBuf,
97 read_only: bool,
98 _lock: Option<File>,
101 catalog: Mutex<CatalogFile>,
104 indexes: OnceLock<Arc<IndexStore>>,
106 default_limit: OnceLock<DefaultLimit>,
108}
109
110pub const INDEX_STORAGE_LIMIT: &str = "ursa.index_storage_limit";
114
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub struct DefaultLimit {
119 pub bytes: u64,
121 pub free: Option<u64>,
124 pub stored: u64,
126}
127
128impl Database {
129 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 pub fn name(&self) -> &str {
212 &self.name
213 }
214
215 pub fn path(&self) -> &Path {
217 &self.path
218 }
219
220 pub fn dir(&self) -> &Path {
223 &self.dir
224 }
225
226 pub fn sidecar_dir(&self) -> &Path {
228 &self.sidecar
229 }
230
231 pub fn index_dir(&self) -> PathBuf {
234 self.sidecar.join("indexes")
235 }
236
237 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 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 pub fn statements(&self) -> Vec<String> {
267 self.catalog().statements.clone()
268 }
269
270 pub fn saved_settings(&self) -> BTreeMap<String, String> {
273 self.catalog().settings.clone()
274 }
275
276 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 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 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 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 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 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 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 fn drop(&mut self) {
397 self.flush();
398 }
399}
400
401pub 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 Ok(url) => url.scheme().len() == 1,
409 Err(_) => true,
410 }
411}
412
413pub fn is_relative_path(location: &str) -> bool {
416 is_local_path(location) && Path::new(location).is_relative()
417}
418
419fn 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 Some(Component::RootDir | Component::Prefix(_)) => {}
432 _ => out.push(".."),
433 },
434 other => out.push(other),
435 }
436 }
437 out
438}
439
440fn 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
450fn 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
466fn 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
494fn 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
504fn 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#[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 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
534pub(crate) fn with_database_slot(config: SessionConfig) -> SessionConfig {
536 config.with_extension(Arc::new(DatabaseSlot::default()))
537}
538
539pub 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
550pub fn database(state: &SessionState) -> Option<Arc<Database>> {
552 database_of_config(state.config())
553}
554
555pub fn database_of_config(config: &SessionConfig) -> Option<Arc<Database>> {
558 config.get_extension::<DatabaseSlot>()?.get()
559}
560
561pub fn flush(state: &SessionState) {
564 if let Some(db) = database(state) {
565 db.flush();
566 }
567}
568
569#[cfg(test)]
570mod tests;