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(csv) = format.downcast_ref::<CsvFormat>() {
402 let o = csv.options();
403 return format!(
404 "csv (header {:?}, delimiter {}, quote {}, terminator {:?}, escape {:?}, \
405 double_quote {:?}, comment {:?}, null_regex {:?}, null_value {:?}, \
406 truncated_rows {:?}, compression {:?}, formats {:?})",
407 o.has_header,
408 o.delimiter,
409 o.quote,
410 o.terminator,
411 o.escape,
412 o.double_quote,
413 o.comment,
414 o.null_regex,
415 o.null_value,
416 o.truncated_rows,
417 o.compression,
418 [
419 &o.date_format,
420 &o.datetime_format,
421 &o.timestamp_format,
422 &o.timestamp_tz_format,
423 &o.time_format
424 ],
425 );
426 }
427 if let Some(json) = format.downcast_ref::<JsonFormat>() {
428 let o = json.options();
429 return format!(
430 "json (newline_delimited {}, compression {:?})",
431 o.newline_delimited, o.compression
432 );
433 }
434 if let Some(parquet) = format.downcast_ref::<ParquetFormat>() {
435 let o = &parquet.options().global;
436 return format!(
437 "parquet (binary_as_string {}, schema_force_view_types {}, coerce_int96 {:?} {:?})",
438 o.binary_as_string, o.schema_force_view_types, o.coerce_int96, o.coerce_int96_tz
439 );
440 }
441 if format.downcast_ref::<ArrowFormat>().is_some() {
442 return "arrow".to_string();
443 }
444 format!("{} {format:?}", format.get_ext())
446}
447
448pub(crate) const DATABASE_DIR: &str = "\u{0}database\u{0}";
453
454fn dir_forms(dir: &Path) -> Vec<String> {
459 let mut forms = Vec::new();
460 let canonical = std::fs::canonicalize(dir).ok();
461 for dir in std::iter::once(dir).chain(canonical.as_deref()) {
462 let text = dir.to_string_lossy().replace('\\', "/");
463 let text = text.trim_end_matches('/');
464 if text.is_empty() {
465 continue;
466 }
467 let url = match text.strip_prefix('/') {
468 Some(rest) => format!("file:///{rest}/"),
469 None => format!("file:///{text}/"),
470 };
471 for form in [url, format!("{text}/")] {
472 if !forms.contains(&form) {
473 forms.push(form);
474 }
475 }
476 }
477 forms.sort_by_key(|f| std::cmp::Reverse(f.len()));
478 forms
479}
480
481pub(crate) fn portable(text: &str, dir: &Path) -> String {
484 let mut text = text.to_string();
485 for form in dir_forms(dir) {
486 text = text.replace(&form, &format!("{DATABASE_DIR}/"));
487 }
488 text
489}
490
491pub(crate) fn portable_in(text: &str, config: &SessionConfig) -> String {
494 match database_of_config(config) {
495 Some(db) => portable(text, db.dir()),
496 None => text.to_string(),
497 }
498}
499
500fn local_path(location: &str) -> String {
503 if cfg!(windows) || location.starts_with('/') {
504 location.to_string()
505 } else {
506 format!("/{location}")
507 }
508}
509
510pub async fn file_identities(
513 plan: &Arc<dyn ExecutionPlan>,
514 context: &TaskContext,
515) -> Result<Vec<FileIdentity>> {
516 let mut files = Vec::new();
517 let _ = plan.apply(|node| {
518 if let Some(config) = node
519 .downcast_ref::<DataSourceExec>()
520 .and_then(|exec| exec.data_source().downcast_ref::<FileScanConfig>())
521 {
522 for group in &config.file_groups {
523 for file in group.files() {
524 files.push((
525 config.object_store_url.clone(),
526 file.object_meta.location.clone(),
527 ));
528 }
529 }
530 }
531 Ok(TreeNodeRecursion::Continue)
532 });
533 files.sort();
534 files.dedup();
535 let database = database_of_config(context.session_config());
536 let mut identities = Vec::with_capacity(files.len());
537 for (url, location) in files {
538 let store = context.runtime_env().object_store(&url)?;
539 let meta = store.head(&location).await?;
540 let store = url.to_string();
541 let location = if store == LOCAL_STORE {
544 let path = local_path(location.as_ref());
545 match &database {
546 Some(db) => portable(&path, db.dir()),
547 None => path,
548 }
549 } else {
550 location.to_string()
551 };
552 identities.push(FileIdentity {
553 store,
554 location,
555 size: meta.size,
556 modified: meta.last_modified.timestamp_nanos_opt().unwrap_or(i64::MAX),
557 e_tag: meta.e_tag,
558 });
559 }
560 identities.sort();
561 Ok(identities)
562}
563
564const LOCAL_STORE: &str = "file:///";
566
567const CAPACITY: usize = 16;
570
571#[derive(Debug, Default)]
573pub struct IndexCache {
574 slots: Mutex<HashMap<String, Slot>>,
575 clock: AtomicU64,
577 builds: AtomicU64,
578 loads: AtomicU64,
579}
580
581#[derive(Debug)]
582struct Slot {
583 files: Vec<FileIdentity>,
584 cell: Arc<tokio::sync::OnceCell<Arc<GraphIndex>>>,
585 used: u64,
586}
587
588impl IndexCache {
589 pub fn builds(&self) -> u64 {
591 self.builds.load(Ordering::Relaxed)
592 }
593
594 pub fn loads(&self) -> u64 {
597 self.loads.load(Ordering::Relaxed)
598 }
599
600 pub fn record_build(&self) {
602 self.builds.fetch_add(1, Ordering::Relaxed);
603 }
604
605 pub fn record_damaged_load(&self) {
608 let _ = self
609 .loads
610 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_sub(1));
611 }
612
613 pub fn get(&self, key: &(String, Vec<FileIdentity>)) -> Option<Arc<GraphIndex>> {
615 let mut slots = self.slots.lock().unwrap_or_else(|e| e.into_inner());
616 let slot = slots.get_mut(&key.0).filter(|s| s.files == key.1)?;
617 let index = slot.cell.get().filter(|i| !i.is_damaged()).cloned()?;
618 slot.used = self.clock.fetch_add(1, Ordering::Relaxed);
619 Some(index)
620 }
621
622 pub fn holds(
626 &self,
627 config: &SessionConfig,
628 key: &(String, Vec<FileIdentity>),
629 ) -> Option<IndexHeld> {
630 let cached = {
631 let slots = self.slots.lock().unwrap_or_else(|e| e.into_inner());
632 slots
633 .get(&key.0)
634 .filter(|s| s.files == key.1)
635 .is_some_and(|s| s.cell.get().is_some_and(|i| !i.is_damaged()))
636 };
637 if cached {
638 return Some(IndexHeld::Cached);
639 }
640 let db = database_of_config(config)?;
641 let stored = IndexKey::new(portable(&key.0, db.dir()), key.1.clone());
642 db.index_store()
643 .contains(&stored)
644 .then_some(IndexHeld::Stored)
645 }
646
647 pub async fn get_or_build(
652 &self,
653 key: Option<(String, Vec<FileIdentity>)>,
654 build: BoxFuture<'_, Result<GraphIndex>>,
655 ) -> Result<Arc<GraphIndex>> {
656 self.get_or_build_in(None, &Notifier::silent(), &BuildInfo::default(), key, build)
657 .await
658 }
659
660 pub async fn get_or_build_stored(
665 &self,
666 config: &SessionConfig,
667 key: Option<(String, Vec<FileIdentity>)>,
668 build: BoxFuture<'_, Result<GraphIndex>>,
669 ) -> Result<Arc<GraphIndex>> {
670 self.get_or_build_for(config, key, &BuildInfo::default(), build)
671 .await
672 }
673
674 pub async fn get_or_build_for(
677 &self,
678 config: &SessionConfig,
679 key: Option<(String, Vec<FileIdentity>)>,
680 info: &BuildInfo,
681 build: BoxFuture<'_, Result<GraphIndex>>,
682 ) -> Result<Arc<GraphIndex>> {
683 let stored = database_of_config(config).map(|db| {
684 db.use_index_storage_limit(config);
686 (db.index_store(), db.dir().to_path_buf())
687 });
688 let notifier = Notifier::of(config);
689 self.get_or_build_in(stored, ¬ifier, info, key, build)
690 .await
691 }
692
693 async fn get_or_build_in(
694 &self,
695 stored: Option<(Arc<IndexStore>, PathBuf)>,
696 notifier: &Notifier,
697 info: &BuildInfo,
698 key: Option<(String, Vec<FileIdentity>)>,
699 build: BoxFuture<'_, Result<GraphIndex>>,
700 ) -> Result<Arc<GraphIndex>> {
701 let Some((fingerprint, files)) = key else {
702 self.builds.fetch_add(1, Ordering::Relaxed);
703 return build_noticed(notifier, info, build, Kept::Never).await;
704 };
705 let stored = stored.map(|(store, dir)| {
708 (
709 store,
710 IndexKey::new(portable(&fingerprint, &dir), files.clone()),
711 )
712 });
713 let cell = {
714 let mut slots = self.slots.lock().unwrap_or_else(|e| e.into_inner());
715 let used = self.clock.fetch_add(1, Ordering::Relaxed);
716 match slots.get_mut(&fingerprint) {
717 Some(slot)
719 if slot.files == files && !slot.cell.get().is_some_and(|i| i.is_damaged()) =>
720 {
721 slot.used = used;
722 Arc::clone(&slot.cell)
723 }
724 _ => {
725 if !slots.contains_key(&fingerprint) && slots.len() >= CAPACITY {
726 if let Some(oldest) = slots
727 .iter()
728 .min_by_key(|(_, s)| s.used)
729 .map(|(k, _)| k.clone())
730 {
731 slots.remove(&oldest);
732 }
733 }
734 let cell = Arc::new(tokio::sync::OnceCell::new());
735 slots.insert(
736 fingerprint,
737 Slot {
738 files,
739 cell: Arc::clone(&cell),
740 used,
741 },
742 );
743 cell
744 }
745 }
746 };
747 let (builds, loads) = (&self.builds, &self.loads);
749 cell.get_or_try_init(|| async move {
750 if let Some((store, key)) = &stored {
751 let (store, key) = (Arc::clone(store), key.clone());
752 let started = clock(notifier, NoticeLevel::All);
753 let reader = notifier.clone();
754 let loaded = crate::run_blocking(move || {
756 let loaded = IndexStore::load(&store, &key, &reader);
757 loaded.map(|(index, size)| (index, size, store))
758 })
759 .await
760 .ok()
761 .flatten();
762 if let Some((index, size, store)) = loaded {
763 loads.fetch_add(1, Ordering::Relaxed);
764 notifier.say(NoticeLevel::All, || {
765 format!(
766 "loaded the index for {} ({} edges) from {} ({}){}",
767 info.graph(),
768 notices::count(index.topology.n_edges() as u64),
769 store.database(),
770 notices::size(size),
771 took(started)
772 )
773 });
774 return Ok(index);
775 }
776 }
777 builds.fetch_add(1, Ordering::Relaxed);
778 let kept = match &stored {
779 Some((store, key)) => Kept::Stored(Arc::clone(store), key.clone()),
780 None => Kept::InMemory,
781 };
782 build_noticed(notifier, info, build, kept).await
783 })
784 .await
785 .cloned()
786 }
787}
788
789#[derive(Debug, Clone, Copy, PartialEq, Eq)]
791pub enum IndexHeld {
792 Cached,
794 Stored,
796}
797
798impl fmt::Display for IndexHeld {
799 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
800 f.write_str(match self {
801 IndexHeld::Cached => "cached",
802 IndexHeld::Stored => "stored",
803 })
804 }
805}
806
807#[derive(Debug, Clone, Default)]
809pub struct BuildInfo {
810 pub graph: Option<String>,
812 pub size: Option<BuildSize>,
814}
815
816#[derive(Debug, Clone, Copy, PartialEq, Eq)]
818pub enum BuildSize {
819 Edges(u64, bool),
821 Reads(u64),
824}
825
826impl BuildInfo {
827 fn graph(&self) -> &str {
828 self.graph.as_deref().unwrap_or("a graph")
829 }
830
831 fn announcement(&self) -> String {
835 let graph = self.graph();
836 match self.size {
837 Some(BuildSize::Edges(n, true)) if n > 0 => {
838 format!(
839 "building the index for {graph} ({} edges)…",
840 notices::count(n)
841 )
842 }
843 Some(BuildSize::Edges(n, false)) if n > 0 => format!(
844 "building the index for {graph} (about {} edges)…",
845 notices::count(n)
846 ),
847 Some(BuildSize::Reads(n)) if n > 0 => format!(
848 "reading about {} rows to build the index for {graph}…",
849 notices::count(n)
850 ),
851 _ => format!("building the index for {graph}…"),
852 }
853 }
854}
855
856enum Kept {
858 Stored(Arc<IndexStore>, IndexKey),
861 InMemory,
863 Never,
865}
866
867fn clock(notifier: &Notifier, level: NoticeLevel) -> Option<Instant> {
870 (notifier.level() >= level).then(Instant::now)
871}
872
873fn took(started: Option<Instant>) -> String {
875 started
876 .map(|s| format!(" in {}", notices::duration(s.elapsed())))
877 .unwrap_or_default()
878}
879
880async fn build_noticed(
886 notifier: &Notifier,
887 info: &BuildInfo,
888 build: BoxFuture<'_, Result<GraphIndex>>,
889 kept: Kept,
890) -> Result<Arc<GraphIndex>> {
891 let started = clock(notifier, NoticeLevel::On);
892 let delay = match notifier.level() {
893 NoticeLevel::All => Duration::ZERO,
894 _ => notices::BUILD_NOTICE_AFTER,
895 };
896 let announcement = notifier.announce_after(delay, info.announcement());
897 let built = build.await;
898 let announced = announcement.finish();
899 let index = Arc::new(built?);
900 let (outcome, loses_work) = match kept {
901 Kept::Stored(store, key) => {
902 let saved = store.save(key, Arc::clone(&index), info.graph(), notifier);
903 (
904 format!("; {}", saved.describe(store.database())),
905 saved.loses_work(),
906 )
907 }
908 Kept::InMemory => (
909 "; kept for this session only (open a .ursa database to store it)".to_string(),
910 false,
911 ),
912 Kept::Never => (
913 "; not kept: what its edges read can change (an in-memory table, or a volatile \
914 function such as random())"
915 .to_string(),
916 false,
917 ),
918 };
919 let level = if announced || loses_work {
920 NoticeLevel::On
921 } else {
922 NoticeLevel::All
923 };
924 notifier.say(level, || {
925 format!(
926 "built the index for {} ({} edges){}{outcome}",
927 info.graph(),
928 notices::count(index.topology.n_edges() as u64),
929 took(started)
930 )
931 });
932 Ok(index)
933}
934
935pub(crate) fn with_index_cache(config: SessionConfig) -> SessionConfig {
937 config.with_extension(Arc::new(IndexCache::default()))
938}
939
940pub fn index_builds(ctx: &SessionContext) -> u64 {
942 ctx.state()
943 .config()
944 .get_extension::<IndexCache>()
945 .map(|c| c.builds())
946 .unwrap_or(0)
947}
948
949pub fn index_loads(ctx: &SessionContext) -> u64 {
952 ctx.state()
953 .config()
954 .get_extension::<IndexCache>()
955 .map(|c| c.loads())
956 .unwrap_or(0)
957}
958
959#[cfg(test)]
960mod tests {
961 use super::*;
962
963 #[test]
964 fn paths_inside_the_database_directory_are_portable() {
965 let dir = Path::new("/home/me/proj");
966 let text =
967 "TableScan: /home/me/proj/edges.csv\npaths [\"file:///home/me/proj/edges.csv\"] \
968 /home/me/project2/x.csv /home/me/proj";
969 assert_eq!(
970 portable(text, dir),
971 format!(
972 "TableScan: {DATABASE_DIR}/edges.csv\npaths [\"{DATABASE_DIR}/edges.csv\"] \
973 /home/me/project2/x.csv /home/me/proj"
974 )
975 );
976 assert_eq!(portable("/a/b.csv", Path::new("/")), "/a/b.csv");
978 assert_eq!(
980 portable("/home/me/proj/edges.csv", dir),
981 portable("/mnt/elsewhere/edges.csv", Path::new("/mnt/elsewhere/"))
982 );
983 }
984
985 #[test]
986 fn local_locations_keep_their_leading_slash() {
987 #[cfg(not(windows))]
988 assert_eq!(local_path("home/me/a.csv"), "/home/me/a.csv");
989 assert_eq!(local_path("/home/me/a.csv"), "/home/me/a.csv");
990 }
991}