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;
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
56pub const DEFAULT_LOCK_TIMEOUT: Duration = Duration::from_secs(2);
58
59#[derive(Debug, Clone)]
61pub struct OpenOptions {
62 pub read_only: bool,
65 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#[derive(Debug)]
90pub struct Database {
91 name: String,
93 path: PathBuf,
95 dir: PathBuf,
98 sidecar: PathBuf,
100 read_only: bool,
101 _lock: Option<File>,
104 catalog: Mutex<CatalogFile>,
107 indexes: OnceLock<Arc<IndexStore>>,
109 default_limit: OnceLock<DefaultLimit>,
111}
112
113pub const INDEX_STORAGE_LIMIT: &str = "ursa.index_storage_limit";
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub struct DefaultLimit {
122 pub bytes: u64,
124 pub free: Option<u64>,
127 pub stored: u64,
129}
130
131impl Database {
132 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 pub fn name(&self) -> &str {
215 &self.name
216 }
217
218 pub fn path(&self) -> &Path {
220 &self.path
221 }
222
223 pub fn dir(&self) -> &Path {
226 &self.dir
227 }
228
229 pub fn sidecar_dir(&self) -> &Path {
231 &self.sidecar
232 }
233
234 pub fn index_dir(&self) -> PathBuf {
237 self.sidecar.join("indexes")
238 }
239
240 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 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 pub fn statements(&self) -> Vec<String> {
270 self.catalog().statements.clone()
271 }
272
273 pub fn saved_settings(&self) -> BTreeMap<String, String> {
276 self.catalog().settings.clone()
277 }
278
279 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 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 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 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 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 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 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 fn drop(&mut self) {
400 self.flush();
401 }
402}
403
404pub 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 Ok(url) => url.scheme().len() == 1,
412 Err(_) => true,
413 }
414}
415
416pub fn is_relative_path(location: &str) -> bool {
419 is_local_path(location) && Path::new(location).is_relative()
420}
421
422fn 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 Some(Component::RootDir | Component::Prefix(_)) => {}
435 _ => out.push(".."),
436 },
437 other => out.push(other),
438 }
439 }
440 out
441}
442
443fn 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
453fn 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
469fn 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
497fn 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
507fn 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#[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 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
537pub(crate) fn with_database_slot(config: SessionConfig) -> SessionConfig {
539 config.with_extension(Arc::new(DatabaseSlot::default()))
540}
541
542pub 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
553pub fn database(state: &SessionState) -> Option<Arc<Database>> {
555 database_of_config(state.config())
556}
557
558pub fn database_of_config(config: &SessionConfig) -> Option<Arc<Database>> {
561 config.get_extension::<DatabaseSlot>()?.get()
562}
563
564pub fn flush(state: &SessionState) {
567 if let Some(db) = database(state) {
568 db.flush();
569 }
570}
571
572#[cfg(test)]
573mod tests;