1use std::collections::HashMap;
51use std::fmt::{self, Write as _};
52use std::path::{Path, PathBuf};
53use std::sync::atomic::{AtomicU64, Ordering};
54use std::sync::{Arc, Mutex, OnceLock};
55use std::time::{Duration, Instant};
56
57use datafusion::arrow::buffer::BooleanBuffer;
58use datafusion::catalog::default_table_source::source_as_provider;
59use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
60use datafusion::datasource::file_format::arrow::ArrowFormat;
61use datafusion::datasource::file_format::csv::CsvFormat;
62use datafusion::datasource::file_format::json::JsonFormat;
63use datafusion::datasource::file_format::parquet::ParquetFormat;
64use datafusion::datasource::file_format::FileFormat as DataFusionFileFormat;
65use datafusion::datasource::listing::ListingTable;
66use datafusion::datasource::physical_plan::FileScanConfig;
67use datafusion::datasource::source::DataSourceExec;
68use datafusion::error::Result;
69use datafusion::execution::TaskContext;
70use datafusion::logical_expr::LogicalPlan;
71use datafusion::physical_plan::ExecutionPlan;
72use datafusion::prelude::{SessionConfig, SessionContext};
73use futures::future::BoxFuture;
74use object_store::ObjectStoreExt;
75use ursa_core::{IdMap, Topology};
76
77use crate::database::mapped::Unverified;
78use crate::database::{database_of_config, IndexKey, IndexStore};
79use crate::notices::{self, NoticeLevel, Notifier};
80
81#[derive(Debug)]
89pub struct GraphIndex {
90 pub topology: Arc<Topology>,
91 pub ids: Arc<IdMap>,
92 n_dropped: u64,
94 kept: Option<BooleanBuffer>,
97 rows: OnceLock<Vec<u64>>,
99 weights: WeightCache,
101 stored: Option<StoredWeights>,
103 unverified: Option<Arc<Unverified>>,
106}
107
108pub type WeightReader = Box<dyn Fn(&str) -> Option<Vec<Vec<f64>>> + Send + Sync>;
111
112struct StoredWeights {
114 keys: Vec<String>,
115 read: WeightReader,
116}
117
118impl fmt::Debug for StoredWeights {
119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120 write!(f, "StoredWeights({} sets)", self.keys.len())
121 }
122}
123
124impl GraphIndex {
125 pub fn new(topology: Arc<Topology>, ids: Arc<IdMap>) -> Self {
126 Self {
127 topology,
128 ids,
129 n_dropped: 0,
130 kept: None,
131 rows: OnceLock::new(),
132 weights: WeightCache::default(),
133 stored: None,
134 unverified: None,
135 }
136 }
137
138 pub fn with_unverified(mut self, unverified: Option<Arc<Unverified>>) -> Self {
141 self.unverified = unverified;
142 self
143 }
144
145 pub fn verify_stored(&self) -> std::result::Result<(), String> {
151 self.unverified.as_ref().map_or(Ok(()), |u| u.verify())
152 }
153
154 pub fn is_damaged(&self) -> bool {
157 self.unverified.as_ref().is_some_and(|u| u.is_damaged())
158 }
159
160 pub fn with_dropped(mut self, n_dropped: u64, kept: Option<BooleanBuffer>) -> Self {
163 self.n_dropped = n_dropped;
164 self.kept = kept.filter(|_| n_dropped > 0);
165 self
166 }
167
168 pub fn n_dropped(&self) -> u64 {
171 self.n_dropped
172 }
173
174 pub fn kept_rows(&self) -> Option<&BooleanBuffer> {
177 self.kept.as_ref()
178 }
179
180 pub fn edge_row(&self, edge: u32) -> u64 {
183 match &self.kept {
184 None => u64::from(edge),
185 Some(kept) => self
186 .rows
187 .get_or_init(|| kept.set_indices().map(|i| i as u64).collect())[edge as usize],
188 }
189 }
190
191 pub fn with_stored_weights(mut self, keys: Vec<String>, read: WeightReader) -> Self {
194 if !keys.is_empty() {
195 self.stored = Some(StoredWeights { keys, read });
196 }
197 self
198 }
199
200 pub fn weights(&self, key: &str) -> Option<Weights> {
202 self.weights.get(key)
203 }
204
205 pub fn has_stored_weights(&self, key: &str) -> bool {
207 self.stored
208 .as_ref()
209 .is_some_and(|s| s.keys.iter().any(|k| k == key))
210 }
211
212 pub fn stored_weights(&self, key: &str, n_columns: usize) -> Option<Weights> {
216 if let Some(weights) = self.weights(key) {
217 return Some(weights);
218 }
219 if !self.has_stored_weights(key) {
220 return None;
221 }
222 let columns = (self.stored.as_ref()?.read)(key)?;
223 let n_edges = self.topology.n_edges();
224 if columns.len() != n_columns || columns.iter().any(|c| c.len() != n_edges) {
225 return None;
226 }
227 let weights: Weights = Arc::new(columns.into_iter().map(Arc::new).collect());
228 self.store_weights(key.to_string(), Arc::clone(&weights));
229 Some(weights)
230 }
231
232 pub fn weight_sets(&self) -> Vec<(String, Weights)> {
234 self.weights.all()
235 }
236
237 pub fn store_weights(&self, key: String, weights: Weights) {
240 self.weights.put(key, weights)
241 }
242}
243
244pub type Weights = Arc<Vec<Arc<Vec<f64>>>>;
247
248const WEIGHT_CAPACITY: usize = 4;
252
253#[derive(Default)]
257struct WeightCache {
258 entries: Mutex<Vec<(String, Weights)>>,
259}
260
261impl fmt::Debug for WeightCache {
262 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263 let entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
264 write!(f, "WeightCache({} entries)", entries.len())
265 }
266}
267
268impl WeightCache {
269 fn get(&self, key: &str) -> Option<Weights> {
270 let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
271 let i = entries.iter().position(|(k, _)| k == key)?;
272 let entry = entries.remove(i);
273 let weights = Arc::clone(&entry.1);
274 entries.push(entry);
275 Some(weights)
276 }
277
278 fn all(&self) -> Vec<(String, Weights)> {
279 let entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
280 entries
281 .iter()
282 .map(|(k, w)| (k.clone(), Arc::clone(w)))
283 .collect()
284 }
285
286 fn put(&self, key: String, weights: Weights) {
287 let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
288 entries.retain(|(k, _)| *k != key);
289 if entries.len() >= WEIGHT_CAPACITY {
290 entries.remove(0);
291 }
292 entries.push((key, weights));
293 }
294}
295
296#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
298pub struct FileIdentity {
299 pub store: String,
300 pub location: String,
301 pub size: u64,
302 pub modified: i64,
304 pub e_tag: Option<String>,
305}
306
307pub fn fingerprint(plan: &LogicalPlan) -> Option<String> {
310 let mut rendered = plan.display_indent_schema().to_string();
311 let mut cacheable = true;
312 let mut locations: Vec<String> = Vec::new();
313 let mut scans: Vec<(String, String)> = Vec::new();
314 let _ = plan.apply_with_subqueries(|node| {
315 if node.expressions().iter().any(|e| e.is_volatile()) {
316 cacheable = false;
317 return Ok(TreeNodeRecursion::Stop);
318 }
319 if let LogicalPlan::TableScan(scan) = node {
320 let listing = source_as_provider(&scan.source)
321 .ok()
322 .and_then(|p| p.downcast_ref::<ListingTable>().map(listing_key));
323 match listing {
324 Some(listing) => {
325 let name = scan.table_name.to_string();
326 scans.push((name.clone(), listing));
327 if crate::paths::looks_like_location(&name) && !locations.contains(&name) {
328 locations.push(name);
329 }
330 }
331 None => {
332 cacheable = false;
333 return Ok(TreeNodeRecursion::Stop);
334 }
335 }
336 }
337 Ok(TreeNodeRecursion::Continue)
338 });
339 if !cacheable {
340 return None;
341 }
342 let placeholder = |name: &str| {
348 locations
349 .iter()
350 .position(|l| l == name)
351 .map(|i| format!("\u{0}file {i}\u{0}"))
352 };
353 let mut by_length: Vec<&String> = locations.iter().collect();
354 by_length.sort_by_key(|name| std::cmp::Reverse(name.len()));
355 for name in by_length {
356 if let Some(placeholder) = placeholder(name) {
357 rendered = rendered.replace(name.as_str(), &placeholder);
358 }
359 }
360 for (name, listing) in &scans {
361 let name = placeholder(name).unwrap_or_else(|| name.clone());
362 let _ = write!(rendered, "\n{name}: {listing}");
363 }
364 Some(rendered)
365}
366
367fn listing_key(table: &ListingTable) -> String {
374 let paths: Vec<String> = table.table_paths().iter().map(|p| p.to_string()).collect();
375 let options = table.options();
376 let partitions: Vec<String> = options
377 .table_partition_cols
378 .iter()
379 .map(|(name, data_type)| format!("{name} {data_type}"))
380 .collect();
381 let order: Vec<String> = options
382 .file_sort_order
383 .iter()
384 .map(|exprs| {
385 exprs
386 .iter()
387 .map(ToString::to_string)
388 .collect::<Vec<_>>()
389 .join(", ")
390 })
391 .collect();
392 format!(
393 "paths {paths:?}; extension {:?}; {}; partitions {partitions:?}; order {order:?}",
394 options.file_extension,
395 format_key(options.format.as_ref())
396 )
397}
398
399fn format_key(format: &dyn DataFusionFileFormat) -> String {
401 if let Some(valid) = format.downcast_ref::<ursa_io::parquet_footer::ValidParquet>() {
403 return format_key(valid.inner().as_ref());
404 }
405 if let Some(csv) = format.downcast_ref::<CsvFormat>() {
406 let o = csv.options();
407 return format!(
408 "csv (header {:?}, delimiter {}, quote {}, terminator {:?}, escape {:?}, \
409 double_quote {:?}, comment {:?}, null_regex {:?}, null_value {:?}, \
410 truncated_rows {:?}, compression {:?}, formats {:?})",
411 o.has_header,
412 o.delimiter,
413 o.quote,
414 o.terminator,
415 o.escape,
416 o.double_quote,
417 o.comment,
418 o.null_regex,
419 o.null_value,
420 o.truncated_rows,
421 o.compression,
422 [
423 &o.date_format,
424 &o.datetime_format,
425 &o.timestamp_format,
426 &o.timestamp_tz_format,
427 &o.time_format
428 ],
429 );
430 }
431 if let Some(json) = format.downcast_ref::<JsonFormat>() {
432 let o = json.options();
433 return format!(
434 "json (newline_delimited {}, compression {:?})",
435 o.newline_delimited, o.compression
436 );
437 }
438 if let Some(parquet) = format.downcast_ref::<ParquetFormat>() {
439 let o = &parquet.options().global;
440 return format!(
441 "parquet (binary_as_string {}, schema_force_view_types {}, coerce_int96 {:?} {:?})",
442 o.binary_as_string, o.schema_force_view_types, o.coerce_int96, o.coerce_int96_tz
443 );
444 }
445 if format.downcast_ref::<ArrowFormat>().is_some() {
446 return "arrow".to_string();
447 }
448 format!("{} {format:?}", format.get_ext())
450}
451
452pub(crate) const DATABASE_DIR: &str = "\u{0}database\u{0}";
457
458fn dir_forms(dir: &Path) -> Vec<String> {
463 let mut forms = Vec::new();
464 let canonical = std::fs::canonicalize(dir).ok();
465 for dir in std::iter::once(dir).chain(canonical.as_deref()) {
466 let text = dir.to_string_lossy().replace('\\', "/");
467 let text = text.trim_end_matches('/');
468 if text.is_empty() {
469 continue;
470 }
471 let url = match text.strip_prefix('/') {
472 Some(rest) => format!("file:///{rest}/"),
473 None => format!("file:///{text}/"),
474 };
475 for form in [url, format!("{text}/")] {
476 if !forms.contains(&form) {
477 forms.push(form);
478 }
479 }
480 }
481 forms.sort_by_key(|f| std::cmp::Reverse(f.len()));
482 forms
483}
484
485pub(crate) fn portable(text: &str, dir: &Path) -> String {
488 let mut text = text.to_string();
489 for form in dir_forms(dir) {
490 text = text.replace(&form, &format!("{DATABASE_DIR}/"));
491 }
492 text
493}
494
495pub(crate) fn portable_in(text: &str, config: &SessionConfig) -> String {
498 match database_of_config(config) {
499 Some(db) => portable(text, db.dir()),
500 None => text.to_string(),
501 }
502}
503
504fn local_path(location: &str) -> String {
507 if cfg!(windows) || location.starts_with('/') {
508 location.to_string()
509 } else {
510 format!("/{location}")
511 }
512}
513
514pub async fn file_identities(
517 plan: &Arc<dyn ExecutionPlan>,
518 context: &TaskContext,
519) -> Result<Vec<FileIdentity>> {
520 let mut files = Vec::new();
521 let _ = plan.apply(|node| {
522 if let Some(config) = node
523 .downcast_ref::<DataSourceExec>()
524 .and_then(|exec| exec.data_source().downcast_ref::<FileScanConfig>())
525 {
526 for group in &config.file_groups {
527 for file in group.files() {
528 files.push((
529 config.object_store_url.clone(),
530 file.object_meta.location.clone(),
531 ));
532 }
533 }
534 }
535 Ok(TreeNodeRecursion::Continue)
536 });
537 files.sort();
538 files.dedup();
539 let database = database_of_config(context.session_config());
540 let mut identities = Vec::with_capacity(files.len());
541 for (url, location) in files {
542 let store = context.runtime_env().object_store(&url)?;
543 let meta = store.head(&location).await?;
544 let store = url.to_string();
545 let location = if store == LOCAL_STORE {
548 let path = local_path(location.as_ref());
549 match &database {
550 Some(db) => portable(&path, db.dir()),
551 None => path,
552 }
553 } else {
554 location.to_string()
555 };
556 identities.push(FileIdentity {
557 store,
558 location,
559 size: meta.size,
560 modified: meta.last_modified.timestamp_nanos_opt().unwrap_or(i64::MAX),
561 e_tag: meta.e_tag,
562 });
563 }
564 identities.sort();
565 Ok(identities)
566}
567
568const LOCAL_STORE: &str = "file:///";
570
571const CAPACITY: usize = 16;
574
575#[derive(Debug, Default)]
577pub struct IndexCache {
578 slots: Mutex<HashMap<String, Slot>>,
579 clock: AtomicU64,
581 builds: AtomicU64,
582 loads: AtomicU64,
583}
584
585#[derive(Debug)]
586struct Slot {
587 files: Vec<FileIdentity>,
588 cell: Arc<tokio::sync::OnceCell<Arc<GraphIndex>>>,
589 used: u64,
590}
591
592impl IndexCache {
593 pub fn builds(&self) -> u64 {
595 self.builds.load(Ordering::Relaxed)
596 }
597
598 pub fn loads(&self) -> u64 {
601 self.loads.load(Ordering::Relaxed)
602 }
603
604 pub fn record_build(&self) {
606 self.builds.fetch_add(1, Ordering::Relaxed);
607 }
608
609 pub fn record_damaged_load(&self) {
612 let _ = self
613 .loads
614 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_sub(1));
615 }
616
617 pub fn get(&self, key: &(String, Vec<FileIdentity>)) -> Option<Arc<GraphIndex>> {
619 let mut slots = self.slots.lock().unwrap_or_else(|e| e.into_inner());
620 let slot = slots.get_mut(&key.0).filter(|s| s.files == key.1)?;
621 let index = slot.cell.get().filter(|i| !i.is_damaged()).cloned()?;
622 slot.used = self.clock.fetch_add(1, Ordering::Relaxed);
623 Some(index)
624 }
625
626 pub fn holds(
630 &self,
631 config: &SessionConfig,
632 key: &(String, Vec<FileIdentity>),
633 ) -> Option<IndexHeld> {
634 let cached = {
635 let slots = self.slots.lock().unwrap_or_else(|e| e.into_inner());
636 slots
637 .get(&key.0)
638 .filter(|s| s.files == key.1)
639 .is_some_and(|s| s.cell.get().is_some_and(|i| !i.is_damaged()))
640 };
641 if cached {
642 return Some(IndexHeld::Cached);
643 }
644 let db = database_of_config(config)?;
645 let stored = IndexKey::new(portable(&key.0, db.dir()), key.1.clone());
646 db.index_store()
647 .contains(&stored)
648 .then_some(IndexHeld::Stored)
649 }
650
651 pub async fn get_or_build(
656 &self,
657 key: Option<(String, Vec<FileIdentity>)>,
658 build: BoxFuture<'_, Result<GraphIndex>>,
659 ) -> Result<Arc<GraphIndex>> {
660 self.get_or_build_in(None, &Notifier::silent(), &BuildInfo::default(), key, build)
661 .await
662 }
663
664 pub async fn get_or_build_stored(
669 &self,
670 config: &SessionConfig,
671 key: Option<(String, Vec<FileIdentity>)>,
672 build: BoxFuture<'_, Result<GraphIndex>>,
673 ) -> Result<Arc<GraphIndex>> {
674 self.get_or_build_for(config, key, &BuildInfo::default(), build)
675 .await
676 }
677
678 pub async fn get_or_build_for(
681 &self,
682 config: &SessionConfig,
683 key: Option<(String, Vec<FileIdentity>)>,
684 info: &BuildInfo,
685 build: BoxFuture<'_, Result<GraphIndex>>,
686 ) -> Result<Arc<GraphIndex>> {
687 let stored = database_of_config(config).map(|db| {
688 db.use_index_storage_limit(config);
690 (db.index_store(), db.dir().to_path_buf())
691 });
692 let notifier = Notifier::of(config);
693 self.get_or_build_in(stored, ¬ifier, info, key, build)
694 .await
695 }
696
697 async fn get_or_build_in(
698 &self,
699 stored: Option<(Arc<IndexStore>, PathBuf)>,
700 notifier: &Notifier,
701 info: &BuildInfo,
702 key: Option<(String, Vec<FileIdentity>)>,
703 build: BoxFuture<'_, Result<GraphIndex>>,
704 ) -> Result<Arc<GraphIndex>> {
705 let Some((fingerprint, files)) = key else {
706 self.builds.fetch_add(1, Ordering::Relaxed);
707 return build_noticed(notifier, info, build, Kept::Never).await;
708 };
709 let stored = stored.map(|(store, dir)| {
712 (
713 store,
714 IndexKey::new(portable(&fingerprint, &dir), files.clone()),
715 )
716 });
717 let cell = {
718 let mut slots = self.slots.lock().unwrap_or_else(|e| e.into_inner());
719 let used = self.clock.fetch_add(1, Ordering::Relaxed);
720 match slots.get_mut(&fingerprint) {
721 Some(slot)
723 if slot.files == files && !slot.cell.get().is_some_and(|i| i.is_damaged()) =>
724 {
725 slot.used = used;
726 Arc::clone(&slot.cell)
727 }
728 _ => {
729 if !slots.contains_key(&fingerprint) && slots.len() >= CAPACITY {
730 if let Some(oldest) = slots
731 .iter()
732 .min_by_key(|(_, s)| s.used)
733 .map(|(k, _)| k.clone())
734 {
735 slots.remove(&oldest);
736 }
737 }
738 let cell = Arc::new(tokio::sync::OnceCell::new());
739 slots.insert(
740 fingerprint,
741 Slot {
742 files,
743 cell: Arc::clone(&cell),
744 used,
745 },
746 );
747 cell
748 }
749 }
750 };
751 let (builds, loads) = (&self.builds, &self.loads);
753 cell.get_or_try_init(|| async move {
754 if let Some((store, key)) = &stored {
755 let (store, key) = (Arc::clone(store), key.clone());
756 let started = clock(notifier, NoticeLevel::All);
757 let reader = notifier.clone();
758 let loaded = crate::run_blocking(move || {
760 let loaded = IndexStore::load(&store, &key, &reader);
761 loaded.map(|(index, size)| (index, size, store))
762 })
763 .await
764 .ok()
765 .flatten();
766 if let Some((index, size, store)) = loaded {
767 loads.fetch_add(1, Ordering::Relaxed);
768 notifier.say(NoticeLevel::All, || {
769 format!(
770 "loaded the index for {} ({} edges) from {} ({}){}",
771 info.graph(),
772 notices::count(index.topology.n_edges() as u64),
773 store.database(),
774 notices::size(size),
775 took(started)
776 )
777 });
778 return Ok(index);
779 }
780 }
781 builds.fetch_add(1, Ordering::Relaxed);
782 let kept = match &stored {
783 Some((store, key)) => Kept::Stored(Arc::clone(store), key.clone()),
784 None => Kept::InMemory,
785 };
786 build_noticed(notifier, info, build, kept).await
787 })
788 .await
789 .cloned()
790 }
791}
792
793#[derive(Debug, Clone, Copy, PartialEq, Eq)]
795pub enum IndexHeld {
796 Cached,
798 Stored,
800}
801
802impl fmt::Display for IndexHeld {
803 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
804 f.write_str(match self {
805 IndexHeld::Cached => "cached",
806 IndexHeld::Stored => "stored",
807 })
808 }
809}
810
811#[derive(Debug, Clone, Default)]
813pub struct BuildInfo {
814 pub graph: Option<String>,
816 pub size: Option<BuildSize>,
818}
819
820#[derive(Debug, Clone, Copy, PartialEq, Eq)]
822pub enum BuildSize {
823 Edges(u64, bool),
825 Reads(u64),
828}
829
830impl BuildInfo {
831 fn graph(&self) -> &str {
832 self.graph.as_deref().unwrap_or("a graph")
833 }
834
835 fn announcement(&self) -> String {
839 let graph = self.graph();
840 match self.size {
841 Some(BuildSize::Edges(n, true)) if n > 0 => {
842 format!(
843 "building the index for {graph} ({} edges)…",
844 notices::count(n)
845 )
846 }
847 Some(BuildSize::Edges(n, false)) if n > 0 => format!(
848 "building the index for {graph} (about {} edges)…",
849 notices::count(n)
850 ),
851 Some(BuildSize::Reads(n)) if n > 0 => format!(
852 "reading about {} rows to build the index for {graph}…",
853 notices::count(n)
854 ),
855 _ => format!("building the index for {graph}…"),
856 }
857 }
858}
859
860enum Kept {
862 Stored(Arc<IndexStore>, IndexKey),
865 InMemory,
867 Never,
869}
870
871fn clock(notifier: &Notifier, level: NoticeLevel) -> Option<Instant> {
874 (notifier.level() >= level).then(Instant::now)
875}
876
877fn took(started: Option<Instant>) -> String {
879 started
880 .map(|s| format!(" in {}", notices::duration(s.elapsed())))
881 .unwrap_or_default()
882}
883
884async fn build_noticed(
890 notifier: &Notifier,
891 info: &BuildInfo,
892 build: BoxFuture<'_, Result<GraphIndex>>,
893 kept: Kept,
894) -> Result<Arc<GraphIndex>> {
895 let started = clock(notifier, NoticeLevel::On);
896 let delay = match notifier.level() {
897 NoticeLevel::All => Duration::ZERO,
898 _ => notices::BUILD_NOTICE_AFTER,
899 };
900 let announcement = notifier.announce_after(delay, info.announcement());
901 let built = build.await;
902 let announced = announcement.finish();
903 let index = Arc::new(built?);
904 let (outcome, loses_work) = match kept {
905 Kept::Stored(store, key) => {
906 let saved = store.save(key, Arc::clone(&index), info.graph(), notifier);
907 (
908 format!("; {}", saved.describe(store.database())),
909 saved.loses_work(),
910 )
911 }
912 Kept::InMemory => (
913 "; kept for this session only (open a .ursa database to store it)".to_string(),
914 false,
915 ),
916 Kept::Never => (
917 "; not kept: what its edges read can change (an in-memory table, or a volatile \
918 function such as random())"
919 .to_string(),
920 false,
921 ),
922 };
923 let level = if announced || loses_work {
924 NoticeLevel::On
925 } else {
926 NoticeLevel::All
927 };
928 notifier.say(level, || {
929 format!(
930 "built the index for {} ({} edges){}{outcome}",
931 info.graph(),
932 notices::count(index.topology.n_edges() as u64),
933 took(started)
934 )
935 });
936 Ok(index)
937}
938
939pub(crate) fn with_index_cache(config: SessionConfig) -> SessionConfig {
941 config.with_extension(Arc::new(IndexCache::default()))
942}
943
944pub fn index_builds(ctx: &SessionContext) -> u64 {
946 ctx.state()
947 .config()
948 .get_extension::<IndexCache>()
949 .map(|c| c.builds())
950 .unwrap_or(0)
951}
952
953pub fn index_loads(ctx: &SessionContext) -> u64 {
956 ctx.state()
957 .config()
958 .get_extension::<IndexCache>()
959 .map(|c| c.loads())
960 .unwrap_or(0)
961}
962
963#[cfg(test)]
964mod tests {
965 use super::*;
966
967 #[test]
968 fn paths_inside_the_database_directory_are_portable() {
969 let dir = Path::new("/home/me/proj");
970 let text =
971 "TableScan: /home/me/proj/edges.csv\npaths [\"file:///home/me/proj/edges.csv\"] \
972 /home/me/project2/x.csv /home/me/proj";
973 assert_eq!(
974 portable(text, dir),
975 format!(
976 "TableScan: {DATABASE_DIR}/edges.csv\npaths [\"{DATABASE_DIR}/edges.csv\"] \
977 /home/me/project2/x.csv /home/me/proj"
978 )
979 );
980 assert_eq!(portable("/a/b.csv", Path::new("/")), "/a/b.csv");
982 assert_eq!(
984 portable("/home/me/proj/edges.csv", dir),
985 portable("/mnt/elsewhere/edges.csv", Path::new("/mnt/elsewhere/"))
986 );
987 }
988
989 #[test]
990 fn local_locations_keep_their_leading_slash() {
991 #[cfg(not(windows))]
992 assert_eq!(local_path("home/me/a.csv"), "/home/me/a.csv");
993 assert_eq!(local_path("/home/me/a.csv"), "/home/me/a.csv");
994 }
995}