1use std::{
3 mem,
4 sync::{
5 Arc,
6 atomic::{AtomicUsize, Ordering},
7 },
8};
9
10use crate::{
11 common::IndexSet,
12 hash_index::IndexCatalog,
13 numeric_id::{DenseIdMap, DenseIdMapWithReuse, NumericId, define_id},
14};
15use crossbeam_queue::SegQueue;
16use egglog_concurrency::{NotificationList, ResettableOnceLock};
17use smallvec::SmallVec;
18
19use crate::{
20 BaseValues, ContainerRebuildSummary, ContainerValues, PoolSet, QueryEntry, TupleIndex, Value,
21 action::{
22 Bindings, DbView,
23 mask::{Mask, MaskIter, ValueSource},
24 },
25 dependency_graph::DependencyGraph,
26 hash_index::{ColumnIndex, Index, IndexBase},
27 offsets::Subset,
28 parallel,
29 parallel_heuristics::parallelize_db_level_op,
30 pool::{Pool, Pooled, with_pool_set},
31 query::{Query, RuleSetBuilder},
32 table_spec::{
33 ColumnId, Constraint, MutationBuffer, Table, TableSpec, WrappedTable, WrappedTableRef,
34 },
35};
36
37use self::packed_cache::{AccessFamilies, FamilyId, SuccessorSig, canonical_constraints};
38use self::packed_trie::ChildShape;
39use self::plan::{Plan, SharedHeaderSubset};
40use crate::action::{ExecutionState, ExternalContext};
41use crate::common::HashMap;
42
43pub(crate) mod execute;
44pub(crate) mod frame_update;
45mod join_tail;
46mod packed_cache;
47mod prepared_index;
48mod probe;
49mod residual_index;
50#[allow(dead_code)]
52pub(crate) mod packed_trie;
53pub(crate) mod plan;
54
55define_id!(
56 pub AtomId,
57 u32,
58 "A component of a query consisting of a function and a list of variables or constants"
59);
60define_id!(pub Variable, u32, "a variable in a query", pretty "Var");
61
62impl Variable {
63 pub fn placeholder() -> Variable {
64 Variable::new(!0)
65 }
66}
67
68define_id!(pub TableId, u32, "a table in the database");
69
70impl TableId {
71 pub fn dummy() -> TableId {
72 TableId::new(u32::MAX)
73 }
74
75 pub fn is_dummy(&self) -> bool {
76 self.rep == u32::MAX
77 }
78}
79
80define_id!(pub(crate) ActionId, u32, "an identifier picking out the RHS of a rule");
81
82#[derive(Debug)]
83pub(crate) struct ProcessedConstraints {
84 pub(crate) subset: SharedHeaderSubset,
88 pub(crate) fast: Pooled<Vec<Constraint>>,
90 pub(crate) slow: Pooled<Vec<Constraint>>,
92}
93
94impl Clone for ProcessedConstraints {
95 fn clone(&self) -> Self {
96 ProcessedConstraints {
97 subset: self.subset.clone(),
98 fast: Pooled::cloned(&self.fast),
99 slow: Pooled::cloned(&self.slow),
100 }
101 }
102}
103
104impl ProcessedConstraints {
105 fn approx_size(&self) -> usize {
107 self.subset.size()
108 }
109
110 pub(crate) fn dummy() -> ProcessedConstraints {
111 ProcessedConstraints {
112 subset: Subset::empty().into(),
113 fast: Pooled::new(Vec::new()),
114 slow: Pooled::new(Vec::new()),
115 }
116 }
117}
118
119pub(crate) type ColumnIds = SmallVec<[ColumnId; 4]>;
123
124#[derive(Clone, Debug, PartialEq, Eq)]
125pub(crate) struct SubAtom {
126 pub(crate) atom: AtomId,
127 pub(crate) vars: ColumnIds,
128}
129
130impl SubAtom {
131 pub(crate) fn new(atom: AtomId) -> SubAtom {
132 SubAtom {
133 atom,
134 vars: Default::default(),
135 }
136 }
137}
138
139#[derive(Debug, Clone)]
140pub(crate) struct VarInfo {
141 pub(crate) occurrences: Vec<SubAtom>,
142 pub(crate) used_in_rhs: bool,
145 pub(crate) defined_in_rhs: bool,
146 pub(crate) name: Option<Arc<str>>,
147}
148
149pub(crate) type HashIndex = Arc<ResettableOnceLock<Index<TupleIndex>>>;
150pub(crate) type HashColumnIndex = Arc<ResettableOnceLock<Index<ColumnIndex>>>;
151
152static NEXT_TABLE_IDENTITY: AtomicUsize = AtomicUsize::new(0);
153
154#[doc(hidden)]
160#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
161pub struct TableIdentity(usize);
162
163impl TableIdentity {
164 fn fresh() -> Self {
165 Self(NEXT_TABLE_IDENTITY.fetch_add(1, Ordering::Relaxed))
166 }
167}
168
169pub struct TableInfo {
170 identity: TableIdentity,
171 pub(crate) name: Option<Arc<str>>,
172 pub(crate) spec: TableSpec,
173 pub(crate) table: WrappedTable,
174 pub(crate) indexes: IndexCatalog<ColumnIds, HashIndex>,
175 pub(crate) column_indexes: IndexCatalog<ColumnId, HashColumnIndex>,
176 successor_families: HashMap<SuccessorSig, FamilyId>,
179}
180
181impl TableInfo {
182 fn successor_family(&mut self, column: ColumnId, constraints: &[Constraint]) -> FamilyId {
184 let next = FamilyId::from_usize(self.successor_families.len());
185 *self
186 .successor_families
187 .entry((column, canonical_constraints(constraints)))
188 .or_insert(next)
189 }
190
191 pub(crate) fn shared_child_shape(&self) -> ChildShape {
196 if self.successor_families.is_empty() {
197 ChildShape::Leaf
198 } else {
199 ChildShape::Dynamic {
200 families: self.successor_families.len(),
201 }
202 }
203 }
204
205 #[doc(hidden)]
206 pub fn identity(&self) -> TableIdentity {
207 self.identity
208 }
209
210 pub fn table(&self) -> &WrappedTable {
211 &self.table
212 }
213
214 pub fn name(&self) -> Option<&str> {
215 self.name.as_deref()
216 }
217
218 pub fn spec(&self) -> &TableSpec {
219 &self.spec
220 }
221}
222
223impl Clone for TableInfo {
224 fn clone(&self) -> Self {
225 fn deep_clone_map<K: Clone + std::hash::Hash + Eq, TI: IndexBase + Clone>(
226 map: &IndexCatalog<K, Arc<ResettableOnceLock<Index<TI>>>>,
227 table: WrappedTableRef,
228 ) -> IndexCatalog<K, Arc<ResettableOnceLock<Index<TI>>>> {
229 map.map(|table_ref| {
230 let (k, v) = table_ref;
231 let v: Index<TI> = v
232 .get_or_update(|index| {
233 index.refresh(table);
234 })
235 .clone();
236 (k.clone(), Arc::new(ResettableOnceLock::new(v)))
237 })
238 }
239 TableInfo {
240 identity: self.identity,
241 name: self.name.clone(),
242 spec: self.spec.clone(),
243 table: self.table.dyn_clone(),
244 indexes: deep_clone_map(&self.indexes, self.table.as_ref()),
245 column_indexes: deep_clone_map(&self.column_indexes, self.table.as_ref()),
246 successor_families: self.successor_families.clone(),
247 }
248 }
249}
250
251define_id!(pub CounterId, u32, "A counter accessible to actions, useful for generating unique Ids.");
252define_id!(pub ExternalFunctionId, u32, "A user-defined operation that can be invoked from a query");
253
254pub trait ExternalFunction: dyn_clone::DynClone + Send + Sync {
260 fn invoke(&self, state: &mut ExecutionState, args: &[Value]) -> Option<Value>;
263}
264
265pub fn make_external_func<
267 F: Fn(&mut ExecutionState, &[Value]) -> Option<Value> + Clone + Send + Sync,
268>(
269 f: F,
270) -> impl ExternalFunction {
271 #[derive(Clone)]
272 struct Wrapped<F>(F);
273 impl<F> ExternalFunction for Wrapped<F>
274 where
275 F: Fn(&mut ExecutionState, &[Value]) -> Option<Value> + Clone + Send + Sync,
276 {
277 fn invoke(&self, state: &mut ExecutionState, args: &[Value]) -> Option<Value> {
278 (self.0)(state, args)
279 }
280 }
281 Wrapped(f)
282}
283
284pub(crate) fn invoke_batch(
286 this: &dyn ExternalFunction,
287 state: &mut ExecutionState,
288 mask: &mut Mask,
289 bindings: &mut Bindings,
290 args: &[QueryEntry],
291 out_var: Variable,
292) {
293 let pool: Pool<Vec<Value>> = with_pool_set(|ps| ps.get_pool());
294 let mut out = pool.get();
295 out.reserve(mask.len());
296 for_each_binding_with_mask!(mask, args, bindings, |iter| {
297 iter.fill_vec(&mut out, Value::stale, |_, args| {
298 this.invoke(state, args.as_slice())
299 });
300 });
301 bindings.insert(out_var, &out);
302}
303
304pub(crate) fn invoke_batch_assign(
310 this: &dyn ExternalFunction,
311 state: &mut ExecutionState,
312 mask: &mut Mask,
313 bindings: &mut Bindings,
314 args: &[QueryEntry],
315 out_var: Variable,
316) {
317 let mut out = bindings.take(out_var).expect("out_var must be bound");
318 for_each_binding_with_mask!(mask, args, bindings, |iter| {
319 iter.assign_vec_and_retain(&mut out.vals, |_, args| this.invoke(state, &args))
320 });
321 bindings.replace(out);
322}
323
324dyn_clone::clone_trait_object!(ExternalFunction);
326
327pub(crate) type ExternalFunctions =
328 DenseIdMapWithReuse<ExternalFunctionId, Box<dyn ExternalFunction>>;
329
330struct Counter {
337 next: AtomicUsize,
338 reservation_size: usize,
339 recycled: SegQueue<std::ops::Range<usize>>,
340}
341
342impl Counter {
343 fn new(reservation_size: usize) -> Self {
344 assert!(reservation_size > 0);
345 Self {
346 next: AtomicUsize::new(0),
347 reservation_size,
348 recycled: SegQueue::new(),
349 }
350 }
351
352 fn take_reservation(&self) -> std::ops::Range<usize> {
353 if self.reservation_size == 1 {
354 let start = self.next.fetch_add(1, Ordering::Release);
355 return start..start + 1;
356 }
357 self.recycled.pop().unwrap_or_else(|| {
358 let start = self
359 .next
360 .fetch_add(self.reservation_size, Ordering::Release);
361 start..start + self.reservation_size
362 })
363 }
364}
365
366pub(crate) struct CounterReservation {
367 counter: Arc<Counter>,
368 range: std::ops::Range<usize>,
369}
370
371impl CounterReservation {
372 fn new(counter: Arc<Counter>) -> Self {
373 let range = counter.take_reservation();
374 Self { counter, range }
375 }
376
377 pub(crate) fn next(&mut self) -> usize {
378 if self.range.start == self.range.end {
379 self.range = self.counter.take_reservation();
380 }
381 let result = self.range.start;
382 self.range.start += 1;
383 result
384 }
385}
386
387impl Drop for CounterReservation {
388 fn drop(&mut self) {
389 if !self.range.is_empty() {
390 self.counter.recycled.push(self.range.clone());
391 }
392 }
393}
394
395#[derive(Default)]
396pub(crate) struct Counters(DenseIdMap<CounterId, Arc<Counter>>);
397
398impl Clone for Counters {
399 fn clone(&self) -> Counters {
400 let mut map = DenseIdMap::new();
401 for (k, v) in self.0.iter() {
402 let cloned = Counter {
404 next: AtomicUsize::new(v.next.load(Ordering::SeqCst)),
405 reservation_size: v.reservation_size,
406 recycled: SegQueue::new(),
410 };
411 map.insert(k, Arc::new(cloned));
412 }
413 Counters(map)
414 }
415}
416
417impl Counters {
418 pub(crate) fn read(&self, ctr: CounterId) -> usize {
419 self.0[ctr].next.load(Ordering::Acquire)
420 }
421 pub(crate) fn inc(&self, ctr: CounterId) -> usize {
422 self.0[ctr].next.fetch_add(1, Ordering::Release)
425 }
426 pub(crate) fn take_reservation(&self, ctr: CounterId) -> CounterReservation {
427 CounterReservation::new(Arc::clone(&self.0[ctr]))
428 }
429}
430
431#[derive(Clone, Default)]
435pub struct Database {
436 pub(crate) tables: DenseIdMap<TableId, TableInfo>,
439 pub(crate) counters: Counters,
442 pub(crate) external_functions: ExternalFunctions,
443 container_values: ContainerValues,
444 notification_list: NotificationList<TableId>,
447 deps: DependencyGraph,
449 base_values: BaseValues,
450 total_size_estimate: usize,
455}
456
457impl Database {
458 pub fn new() -> Database {
463 Database::default()
464 }
465
466 pub fn new_rule_set(&mut self) -> RuleSetBuilder<'_> {
468 RuleSetBuilder::new(self)
469 }
470
471 pub fn add_external_function(
473 &mut self,
474 f: Box<dyn ExternalFunction + 'static>,
475 ) -> ExternalFunctionId {
476 self.external_functions.push(f)
477 }
478
479 pub fn free_external_function(&mut self, id: ExternalFunctionId) {
481 self.external_functions.take(id);
482 }
483
484 pub fn base_values(&self) -> &BaseValues {
485 &self.base_values
486 }
487
488 pub fn base_values_mut(&mut self) -> &mut BaseValues {
489 &mut self.base_values
490 }
491
492 pub fn container_values(&self) -> &ContainerValues {
493 &self.container_values
494 }
495
496 pub fn container_values_mut(&mut self) -> &mut ContainerValues {
497 &mut self.container_values
498 }
499
500 pub fn rebuild_containers(&mut self, table_id: TableId) -> ContainerRebuildSummary {
501 let mut containers = mem::take(&mut self.container_values);
502 let table = &self.tables[table_id].table;
503 let res =
504 self.with_execution_state(None, |state| containers.rebuild_all(table_id, table, state));
505 self.container_values = containers;
506 res
507 }
508
509 pub fn apply_rebuild(
516 &mut self,
517 func_id: TableId,
518 to_rebuild: &[TableId],
519 next_ts: Value,
520 ) -> bool {
521 let func = self.tables.take(func_id).unwrap();
522 self.run_on_tables(to_rebuild, |_, info, view| {
523 info.table.apply_rebuild(
524 func_id,
525 &func.table,
526 next_ts,
527 &mut ExecutionState::new(*view, Default::default()),
528 )
529 });
530 self.tables.insert(func_id, func);
531 self.merge_all()
532 }
533
534 pub fn refresh_rows_for_values(
535 &mut self,
536 to_refresh: &[TableId],
537 dirty_ids: &[Value],
538 next_ts: Value,
539 ) -> bool {
540 if dirty_ids.is_empty() {
541 return false;
542 }
543 self.run_on_tables(to_refresh, |_, info, _| {
551 info.table.refresh_rows_for_values(dirty_ids, next_ts)
552 });
553 self.merge_all()
554 }
555
556 fn run_on_tables(
557 &mut self,
558 table_ids: &[TableId],
559 run: impl for<'a> Fn(TableId, &mut TableInfo, &DbView<'a>) -> bool + Sync,
560 ) {
561 if parallelize_db_level_op(self.total_size_estimate) {
562 let mut tables = Vec::with_capacity(table_ids.len());
563 for id in table_ids {
564 tables.push((*id, self.tables.take(*id).unwrap()));
565 }
566 let view = self.read_only_view();
567 parallel::for_each_mut(&mut tables, |_, (id, info)| {
568 if run(*id, info, &view) {
569 self.notification_list.notify(*id);
570 }
571 });
572 for (id, info) in tables {
573 self.tables.insert(id, info);
574 }
575 } else {
576 for id in table_ids {
577 let mut info = self.tables.take(*id).unwrap();
578 let changed = {
579 let view = self.read_only_view();
580 run(*id, &mut info, &view)
581 };
582 if changed {
583 self.notification_list.notify(*id);
584 }
585 self.tables.insert(*id, info);
586 }
587 }
588 }
589
590 pub fn with_execution_state<R>(
595 &self,
596 context: ExternalContext<'_>,
597 f: impl FnOnce(&mut ExecutionState) -> R,
598 ) -> R {
599 let mut state = ExecutionState::new(self.read_only_view_with(context), Default::default());
600 f(&mut state)
601 }
602
603 pub fn with_execution_state_tracked<R>(
608 &self,
609 context: ExternalContext<'_>,
610 f: impl FnOnce(&mut ExecutionState) -> R,
611 ) -> (R, bool) {
612 let mut state = ExecutionState::new(self.read_only_view_with(context), Default::default());
613 let result = f(&mut state);
614 (result, state.changed)
615 }
616
617 pub(crate) fn read_only_view(&self) -> DbView<'_> {
618 self.read_only_view_with(None)
619 }
620
621 pub(crate) fn read_only_view_with<'a>(&'a self, context: ExternalContext<'a>) -> DbView<'a> {
624 DbView {
625 external_context: context,
626 table_info: &self.tables,
627 counters: &self.counters,
628 external_funcs: &self.external_functions,
629 bases: &self.base_values,
630 containers: &self.container_values,
631 notification_list: &self.notification_list,
632 }
633 }
634
635 pub fn estimate_size(&self, table: TableId, c: Option<Constraint>) -> usize {
638 let table_info = self
639 .tables
640 .get(table)
641 .expect("table must be declared in the current database");
642 let table = &table_info.table;
643 if let Some(c) = c {
644 if let Some(sub) = table.fast_subset(&c) {
645 sub.size()
648 } else {
649 table.refine_one(table.refine_live(table.all()), &c).size()
650 }
651 } else {
652 table.len()
653 }
654 }
655
656 pub fn add_counter(&mut self) -> CounterId {
660 self.counters.0.push(Arc::new(Counter::new(1)))
661 }
662
663 pub fn add_reservable_counter(&mut self, reservation_size: usize) -> CounterId {
675 self.counters
676 .0
677 .push(Arc::new(Counter::new(reservation_size)))
678 }
679
680 pub fn inc_counter(&self, counter: CounterId) -> usize {
682 self.counters.inc(counter)
683 }
684
685 pub fn read_counter(&self, counter: CounterId) -> usize {
687 self.counters.read(counter)
688 }
689
690 pub fn merge_all(&mut self) -> bool {
697 let mut ever_changed = false;
698 let do_parallel = parallelize_db_level_op(self.total_size_estimate);
699 let mut to_merge = IndexSet::default();
700 let mut touched: IndexSet<TableId> = IndexSet::default();
703 loop {
704 to_merge.clear();
705 let to_merge_vec = self.notification_list.reset();
706 touched.extend(to_merge_vec.iter().copied());
707 if to_merge_vec.len() < 4 {
708 ever_changed |= self.merge_simple(to_merge_vec, &mut touched);
709 break;
710 }
711 for table in to_merge_vec {
712 to_merge.insert(table);
713 }
714
715 let mut changed = false;
716 let mut tables_merging = DenseIdMap::<
717 TableId,
718 (
719 Option<TableInfo>,
721 DenseIdMap<TableId, Box<dyn MutationBuffer>>,
724 ),
725 >::with_capacity(self.tables.n_ids());
726 for stratum in self.deps.strata() {
727 for table in stratum.intersection(&to_merge).copied() {
729 let mut bufs = DenseIdMap::default();
730 for dep in self.deps.write_deps(table) {
731 if let Some(info) = self.tables.get(dep) {
732 bufs.insert(dep, info.table.new_buffer());
733 }
734 }
735 tables_merging.insert(table, (None, bufs));
736 }
737 for table in stratum.intersection(&to_merge).copied() {
740 let val = self.tables.unwrap_val(table);
741 self.total_size_estimate =
745 self.total_size_estimate.wrapping_sub(val.table.len());
746 tables_merging[table].0 = Some(val);
747 }
748 let db = self.read_only_view();
749 changed |= if do_parallel {
750 parallel::map_dense_id_map_mut(&mut tables_merging, |_, (info, buffers)| {
751 let mut es = ExecutionState::new(db, mem::take(buffers));
752 info.as_mut().unwrap().table.merge(&mut es).added || es.changed
753 })
754 .into_iter()
755 .any(|changed| changed)
756 } else {
757 tables_merging
758 .iter_mut()
759 .map(|(_, (info, buffers))| {
760 let mut es = ExecutionState::new(db, mem::take(buffers));
761 info.as_mut().unwrap().table.merge(&mut es).added || es.changed
762 })
763 .max()
764 .unwrap_or(false)
765 };
766 for (id, (table, _)) in tables_merging.drain() {
767 let val = table.unwrap();
768 self.total_size_estimate =
769 self.total_size_estimate.wrapping_add(val.table.len());
770 self.tables.insert(id, val);
771 }
772 }
773 ever_changed |= changed;
774 }
775 for table in touched.iter().copied() {
785 if let Some(info) = self.tables.get_mut(table) {
786 info.column_indexes.update(|_, ti| {
787 Arc::get_mut(ti).unwrap().reset();
788 });
789 info.indexes.update(|_, ti| {
790 Arc::get_mut(ti).unwrap().reset();
791 });
792 }
793 }
794 ever_changed
795 }
796
797 fn merge_simple(
801 &mut self,
802 mut to_merge: SmallVec<[TableId; 4]>,
803 touched: &mut IndexSet<TableId>,
804 ) -> bool {
805 let mut changed = false;
806 while !to_merge.is_empty() {
807 for table_id in to_merge.iter().copied() {
808 let mut info = self.tables.unwrap_val(table_id);
809 self.total_size_estimate = self.total_size_estimate.wrapping_sub(info.table.len());
812 let mut es = ExecutionState::new(self.read_only_view(), Default::default());
813 changed |= info.table.merge(&mut es).added || es.changed;
814 self.total_size_estimate = self.total_size_estimate.wrapping_add(info.table.len());
815 self.tables.insert(table_id, info);
816 }
817 to_merge = self.notification_list.reset();
818 touched.extend(to_merge.iter().copied());
819 }
820 changed
821 }
822
823 pub fn merge_table(&mut self, table: TableId) -> bool {
830 let mut info = self.tables.unwrap_val(table);
831 self.total_size_estimate = self.total_size_estimate.wrapping_sub(info.table.len());
832 let table_changed = info.table.merge(&mut ExecutionState::new(
833 self.read_only_view(),
834 Default::default(),
835 ));
836 self.total_size_estimate = self.total_size_estimate.wrapping_add(info.table.len());
837 self.tables.insert(table, info);
838 table_changed.added
839 }
840
841 pub fn next_table_id(&self) -> TableId {
846 self.tables.next_id()
847 }
848
849 pub fn add_table<T: Table + Sized + 'static>(
854 &mut self,
855 table: T,
856 read_deps: impl IntoIterator<Item = TableId>,
857 write_deps: impl IntoIterator<Item = TableId>,
858 ) -> TableId {
859 self.add_table_impl(table, None, read_deps, write_deps)
860 }
861
862 pub fn add_table_named<T: Table + Sized + 'static>(
863 &mut self,
864 table: T,
865 name: Arc<str>,
866 read_deps: impl IntoIterator<Item = TableId>,
867 write_deps: impl IntoIterator<Item = TableId>,
868 ) -> TableId {
869 self.add_table_impl(table, Some(name), read_deps, write_deps)
870 }
871
872 fn add_table_impl<T: Table + Sized + 'static>(
873 &mut self,
874 table: T,
875 name: Option<Arc<str>>,
876 read_deps: impl IntoIterator<Item = TableId>,
877 write_deps: impl IntoIterator<Item = TableId>,
878 ) -> TableId {
879 let spec = table.spec();
880 let table = WrappedTable::new(table);
881 let res = self.tables.push(TableInfo {
882 identity: TableIdentity::fresh(),
883 name,
884 spec,
885 table,
886 indexes: IndexCatalog::new(),
887 column_indexes: IndexCatalog::new(),
888 successor_families: HashMap::default(),
889 });
890 self.deps.add_table(res, read_deps, write_deps);
891 res
892 }
893
894 pub fn get_table(&self, table: TableId) -> &WrappedTable {
909 &self
910 .tables
911 .get(table)
912 .expect("must access a table that has been declared in this database")
913 .table
914 }
915
916 pub fn get_table_info(&self, table: TableId) -> &TableInfo {
921 self.tables
922 .get(table)
923 .expect("must access a table that has been declared in this database")
924 }
925
926 pub fn new_buffer(&self, id: TableId) -> Box<dyn MutationBuffer> {
932 self.notification_list.notify(id);
933 self.get_table(id).new_buffer()
934 }
935
936 pub(crate) fn process_constraints(
937 &self,
938 table: TableId,
939 cs: &[Constraint],
940 ) -> ProcessedConstraints {
941 let table_info = &self.tables[table];
942 let (mut subset, mut fast, mut slow) = table_info.table.split_fast_slow(cs);
943 slow.retain(|c| {
944 let (col, val) = match c {
945 Constraint::EqConst { col, val } => (*col, *val),
946 Constraint::Eq { .. }
947 | Constraint::LtConst { .. }
948 | Constraint::GtConst { .. }
949 | Constraint::LeConst { .. }
950 | Constraint::GeConst { .. } => return true,
951 };
952 if *table_info
955 .spec
956 .uncacheable_columns
957 .get(col)
958 .unwrap_or(&false)
959 {
960 return true;
961 }
962 fast.push(c.clone());
965 let index = get_column_index_from_tableinfo(table_info, col);
966 match index.get().unwrap().get_subset(&val) {
967 Some(s) => {
968 with_pool_set(|ps| subset.intersect(s, &ps.get_pool()));
969 }
970 None => {
971 subset = Subset::empty();
973 }
974 }
975 false
977 });
978 ProcessedConstraints {
979 subset: subset.into(),
980 fast,
981 slow,
982 }
983 }
984
985 pub fn get_table_mut(&mut self, id: TableId) -> &mut dyn Table {
992 &mut *self
993 .tables
994 .get_mut(id)
995 .expect("must access a table that has been declared in this database")
996 .table
997 }
998
999 pub fn clear_table(&mut self, table: TableId) {
1017 let info = self
1018 .tables
1019 .get_mut(table)
1020 .expect("must access a table that has been declared in this database");
1021 let prev_len = info.table.len();
1022 info.table.clear();
1023 info.column_indexes.update(|_, ti| {
1028 if let Some(arc) = Arc::get_mut(ti) {
1029 arc.reset();
1030 }
1031 });
1032 info.indexes.update(|_, ti| {
1033 if let Some(arc) = Arc::get_mut(ti) {
1034 arc.reset();
1035 }
1036 });
1037 self.total_size_estimate = self.total_size_estimate.wrapping_sub(prev_len);
1038 }
1039
1040 pub(crate) fn plan_query(&mut self, query: Query) -> Plan {
1041 let mut plan = plan::plan_query(query, ColumnCardEst::new(self));
1042 let atoms = plan.atoms();
1046 plan.for_each_stages_mut(|stages| {
1047 let mut families = Vec::new();
1048 stages.for_each_indexed_access(|atom, columns, constraints| {
1049 let info = &mut self.tables[atoms[atom].table];
1050 let mut access = AccessFamilies::new();
1051 access.push(info.successor_family(columns[0], constraints));
1052 access.extend(
1053 columns[1..]
1054 .iter()
1055 .map(|column| info.successor_family(*column, &[])),
1056 );
1057 families.push(access);
1058 });
1059 stages.set_families(families.into());
1060 });
1061 plan
1062 }
1063}
1064
1065impl Drop for Database {
1066 fn drop(&mut self) {
1067 with_pool_set(PoolSet::clear);
1069 }
1070}
1071
1072fn get_index_from_tableinfo(table_info: &TableInfo, cols: &[ColumnId]) -> HashIndex {
1077 let index: Arc<_> = table_info.indexes.get_or_insert(cols.into(), || {
1078 Arc::new(ResettableOnceLock::new(Index::new(
1079 cols.to_vec(),
1080 TupleIndex::new(cols.len()),
1081 )))
1082 });
1083 index.get_or_update(|index| {
1084 index.refresh(table_info.table.as_ref());
1085 });
1086 debug_assert!(
1087 !index
1088 .get()
1089 .unwrap()
1090 .needs_refresh(table_info.table.as_ref())
1091 );
1092 index
1093}
1094
1095pub(crate) fn get_column_index_from_tableinfo(
1099 table_info: &TableInfo,
1100 col: ColumnId,
1101) -> HashColumnIndex {
1102 let index: Arc<_> = table_info.column_indexes.get_or_insert(col, || {
1103 Arc::new(ResettableOnceLock::new(Index::new(
1104 vec![col],
1105 ColumnIndex::new(),
1106 )))
1107 });
1108 index.get_or_update(|index| {
1109 index.refresh(table_info.table.as_ref());
1110 });
1111 debug_assert!(
1112 !index
1113 .get()
1114 .unwrap()
1115 .needs_refresh(table_info.table.as_ref())
1116 );
1117 index
1118}
1119
1120#[derive(Clone)]
1121pub struct ColumnCardEst<'a> {
1122 db: &'a Database,
1123}
1124
1125impl ColumnCardEst<'_> {
1126 pub fn new(db: &Database) -> ColumnCardEst<'_> {
1127 ColumnCardEst { db }
1128 }
1129
1130 pub fn col_uniqueness(&self, table: TableId, col: ColumnId) -> ColUniqueness {
1131 let col_idx = get_column_index_from_tableinfo(&self.db.tables[table], col);
1132 let table = &self.db.tables[table].table;
1133 ColUniqueness {
1134 col_size: col_idx.get().unwrap().len(),
1135 table_size: table.len(),
1136 }
1137 }
1138}
1139
1140impl std::fmt::Debug for ColumnCardEst<'_> {
1141 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1142 f.debug_struct("ColumnCardEst").finish_non_exhaustive()
1143 }
1144}
1145
1146#[derive(Copy, Clone, Debug)]
1158pub struct ColUniqueness {
1159 table_size: usize,
1160 col_size: usize,
1161}
1162
1163impl Default for ColUniqueness {
1164 fn default() -> ColUniqueness {
1165 ColUniqueness {
1166 table_size: 1,
1167 col_size: 1,
1168 }
1169 }
1170}
1171
1172impl ColUniqueness {
1173 #[allow(dead_code)] fn scale(&self, subset_size: usize) -> ColUniqueness {
1175 if self.table_size == 0 || subset_size == 0 {
1176 return ColUniqueness {
1177 table_size: 0,
1178 col_size: 0,
1179 };
1180 }
1181 ColUniqueness {
1182 table_size: subset_size,
1183 col_size: self.col_size.saturating_mul(subset_size) / self.table_size,
1184 }
1185 }
1186 fn join(&self, other: &ColUniqueness) -> ColUniqueness {
1187 ColUniqueness {
1188 table_size: self.table_size.saturating_mul(other.table_size),
1189 col_size: self.col_size.max(other.col_size),
1190 }
1191 }
1192
1193 #[allow(dead_code)] fn col_size(&self) -> usize {
1195 self.col_size
1196 }
1197}
1198
1199impl PartialEq for ColUniqueness {
1200 fn eq(&self, other: &Self) -> bool {
1201 self.cmp(other) == std::cmp::Ordering::Equal
1202 }
1203}
1204
1205impl Eq for ColUniqueness {}
1206
1207impl PartialOrd for ColUniqueness {
1208 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1209 Some(self.cmp(other))
1210 }
1211}
1212
1213impl Ord for ColUniqueness {
1214 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1215 (self.table_size.saturating_mul(other.col_size))
1216 .cmp(&(other.table_size.saturating_mul(self.col_size)))
1217 }
1218}