datafusion_execution/cache/
mod.rs1pub mod cache_manager;
6pub mod lru_queue;
7
8pub mod default_cache;
9
10use datafusion_common::arrow::datatypes::{DataType, Schema};
11use datafusion_common::heap_size::{DFHeapSize, DFHeapSizeCtx};
12use datafusion_common::instant::Instant;
13use datafusion_common::{HashMap, TableReference};
14use object_store::path::Path;
15use std::collections::hash_map::DefaultHasher;
16use std::fmt::{Debug, Display, Formatter};
17use std::hash::{Hash, Hasher};
18use std::time::Duration;
19
20pub trait Cache<K: CacheKey, V: CacheValue>: Send + Sync {
31 fn get(&self, key: &K) -> Option<V>;
33
34 fn put(&self, key: &K, value: V) -> Option<V>;
38
39 fn remove(&self, k: &K) -> Option<V>;
41
42 fn contains_key(&self, k: &K) -> bool;
44
45 fn len(&self) -> usize;
47
48 fn is_empty(&self) -> bool {
50 self.len() == 0
51 }
52
53 fn clear(&self);
55
56 fn name(&self) -> String;
58
59 fn cache_limit(&self) -> usize;
61
62 fn update_cache_limit(&self, limit: usize);
64
65 fn cache_ttl(&self) -> Option<Duration>;
68
69 fn update_cache_ttl(&self, _ttl: Option<Duration>);
71
72 fn drop_table_entries(
74 &self,
75 table_ref: &TableReference,
76 ) -> datafusion_common::Result<()>;
77
78 fn list_entries(&self) -> HashMap<K, CacheEntryInfo<V>>;
81}
82
83pub trait CacheKey: Clone + Eq + Hash + Send + Sync + Debug {
85 fn size(&self) -> usize;
87
88 fn table_ref(&self) -> Option<&TableReference>;
91}
92
93pub trait CacheValue: Clone + Send + Sync {
95 fn size(&self) -> usize;
97}
98
99#[derive(Clone, Debug, PartialEq, Eq)]
100pub struct CacheEntryInfo<V> {
101 pub value: V,
102 pub size_bytes: usize,
103 pub hits: usize,
104 pub expires: Option<Instant>,
105}
106
107impl<K: CacheKey, V: CacheValue> Debug for dyn Cache<K, V> {
108 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
109 write!(f, "Cache name: {} with length: {}", self.name(), self.len())
110 }
111}
112
113impl CacheKey for Path {
114 fn size(&self) -> usize {
115 self.as_ref().heap_size(&mut DFHeapSizeCtx::default())
116 }
117
118 fn table_ref(&self) -> Option<&TableReference> {
119 None
120 }
121}
122
123impl CacheKey for TableScopedPath {
124 fn size(&self) -> usize {
125 DFHeapSize::heap_size(self, &mut DFHeapSizeCtx::default())
126 }
127
128 fn table_ref(&self) -> Option<&TableReference> {
129 self.table.as_ref()
130 }
131}
132
133#[derive(PartialEq, Eq, Hash, Clone, Debug)]
137pub struct TableScopedPath {
138 pub table: Option<TableReference>,
139 pub path: Path,
140}
141
142impl DFHeapSize for TableScopedPath {
143 fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
144 self.path.as_ref().heap_size(ctx) + self.table.heap_size(ctx)
145 }
146}
147
148impl Display for TableScopedPath {
149 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
150 if let Some(table) = &self.table {
151 write!(f, "{}, {}", self.path, table)
152 } else {
153 write!(f, "{}", self.path)
154 }
155 }
156}
157
158#[derive(Clone, Debug)]
165pub struct SchemaFingerprint {
166 columns: Vec<(String, DataType, bool)>,
167 hash: u64,
173}
174
175impl SchemaFingerprint {
176 pub fn from_schema(file_schema: &Schema) -> Self {
180 let columns: Vec<(String, DataType, bool)> = file_schema
181 .fields()
182 .iter()
183 .map(|f| (f.name().clone(), f.data_type().clone(), f.is_nullable()))
184 .collect();
185 let mut hasher = DefaultHasher::new();
186 columns.hash(&mut hasher);
187 Self {
188 columns,
189 hash: hasher.finish(),
190 }
191 }
192}
193
194impl PartialEq for SchemaFingerprint {
195 fn eq(&self, other: &Self) -> bool {
196 self.hash == other.hash && self.columns == other.columns
198 }
199}
200
201impl Eq for SchemaFingerprint {}
202
203impl Hash for SchemaFingerprint {
204 fn hash<H: Hasher>(&self, state: &mut H) {
205 state.write_u64(self.hash);
206 }
207}
208
209impl DFHeapSize for SchemaFingerprint {
210 fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
211 self.columns.heap_size(ctx)
212 }
213}
214
215#[cfg(test)]
216mod schema_fingerprint_tests {
217 use super::*;
218 use datafusion_common::arrow::datatypes::{Field, Metadata};
219
220 fn fp(fields: Vec<Field>) -> SchemaFingerprint {
221 SchemaFingerprint::from_schema(&Schema::new(fields))
222 }
223
224 #[test]
227 fn fingerprint_captures_nullability_and_order() {
228 assert_ne!(
229 fp(vec![Field::new("id", DataType::Int64, false)]),
230 fp(vec![Field::new("id", DataType::Int64, true)]),
231 "nullability must affect the fingerprint",
232 );
233
234 let ab = fp(vec![
235 Field::new("a", DataType::Int64, false),
236 Field::new("b", DataType::Utf8, true),
237 ]);
238 let ba = fp(vec![
239 Field::new("b", DataType::Utf8, true),
240 Field::new("a", DataType::Int64, false),
241 ]);
242 assert_ne!(ab, ba, "field order must affect the fingerprint");
243 }
244
245 #[test]
248 fn fingerprint_ignores_metadata() {
249 let plain = fp(vec![Field::new("id", DataType::Int64, false)]);
250
251 let field_md = SchemaFingerprint::from_schema(&Schema::new(vec![
252 Field::new("id", DataType::Int64, false)
253 .with_metadata(Metadata::new().with("note", "x")),
254 ]));
255 assert_eq!(plain, field_md, "field metadata must be ignored");
256
257 let schema_md = SchemaFingerprint::from_schema(
258 &Schema::new(vec![Field::new("id", DataType::Int64, false)])
259 .with_metadata(Metadata::new().with("k", "v")),
260 );
261 assert_eq!(plain, schema_md, "schema metadata must be ignored");
262 }
263}