egglog_core_relations/
query.rs

1//! APIs for building a query of a database.
2
3use std::{iter::once, sync::Arc};
4
5use crate::{
6    free_join::plan::{DecomposedPlan, JoinStageBlocks, SinglePlan},
7    numeric_id::{DenseIdMap, IdVec, NumericId, define_id},
8};
9use smallvec::SmallVec;
10use thiserror::Error;
11
12use crate::{
13    BaseValueId, CounterId, ExternalFunctionId, PoolSet,
14    action::{Instr, QueryEntry, WriteVal},
15    common::HashMap,
16    free_join::{
17        ActionId, AtomId, Database, ProcessedConstraints, SubAtom, TableId, TableInfo, VarInfo,
18        Variable,
19        plan::{JoinHeader, Plan, PlanStrategy, SharedHeaderSubset},
20    },
21    pool::{Pooled, with_pool_set},
22    table_spec::{ColumnId, Constraint},
23};
24
25#[cfg(test)]
26mod tests;
27
28define_id!(pub RuleId, u32, "An identifier for a rule in a rule set");
29
30/// Resolves variables and atoms in a rule to their string names.
31#[allow(dead_code)]
32#[derive(Debug, Clone)]
33pub struct SymbolMap {
34    pub atoms: HashMap<AtomId, Arc<str>>,
35    pub vars: HashMap<Variable, Arc<str>>,
36}
37
38/// A cached plan for a given rule.
39pub struct CachedPlan {
40    plan: Plan,
41    desc: Arc<str>,
42    symbol_map: SymbolMap,
43    actions: ActionInfo,
44}
45
46#[derive(Debug, Clone)]
47pub(crate) struct ActionInfo {
48    pub(crate) used_vars: SmallVec<[Variable; 4]>,
49    pub(crate) instrs: Arc<Pooled<Vec<Instr>>>,
50}
51
52/// A set of rules to run against a [`Database`].
53///
54/// See [`Database::new_rule_set`] for more information.
55#[derive(Default)]
56pub struct RuleSet {
57    /// The contents of the queries (i.e. the LHS of the rules) for each rule in the set, along
58    /// with a description of the rule.
59    ///
60    /// The action here is used to map between rule descriptions and plans, which contain ActionIds. The current
61    /// accounting logic assumes that rules and actions stand in a bijection. If we relaxed that
62    /// later on, most of the core logic would still work but the accounting logic could get more
63    /// complex.
64    pub(crate) plans: IdVec<RuleId, (Plan, Arc<str> /* description */, SymbolMap)>,
65    pub(crate) actions: DenseIdMap<ActionId, ActionInfo>,
66}
67
68impl RuleSet {
69    pub fn build_cached_plan(&self, rule_id: RuleId) -> CachedPlan {
70        let (plan, desc, symbol_map) = self.plans.get(rule_id).expect("rule must exist");
71        let actions = self
72            .actions
73            .get(plan.actions())
74            .expect("action must exist")
75            .clone();
76        CachedPlan {
77            plan: plan.clone(),
78            desc: desc.clone(),
79            symbol_map: symbol_map.clone(),
80            actions,
81        }
82    }
83}
84
85/// Builder for a [`RuleSet`].
86///
87/// There are in general two ways to add rules to a rule set:
88///
89/// 1. Use the QueryBuilder and RuleBuilder APIs to construct a rule from scratch.
90/// 2. Use a previously cached plan and add extra constraints to it.
91///
92/// The pattern this is used by egglog is as follows: An egglog rule is first compiled to a cached
93/// plan using builder patterns at declaration time, and each time the rule is run, it is added to
94/// a ruleset using the cached plan and possibly some extra constraints (e.g., timestamp).
95///
96/// See [`Database::new_rule_set`] for more information.
97pub struct RuleSetBuilder<'outer> {
98    rule_set: RuleSet,
99    db: &'outer mut Database,
100    /// Rows cannot change through this builder. Cache processed headers only
101    /// until it is consumed; the next ruleset rechecks the database after merge.
102    /// Constraint order is preserved, and atom ids deliberately are not keys.
103    header_cache: DenseIdMap<TableId, HashMap<Vec<Constraint>, Option<CachedHeaderConstraints>>>,
104}
105
106struct CachedHeaderConstraints {
107    fast: Pooled<Vec<Constraint>>,
108    subset: SharedHeaderSubset,
109}
110
111impl CachedHeaderConstraints {
112    fn header(&self, atom: AtomId) -> JoinHeader {
113        JoinHeader {
114            atom,
115            constraints: Pooled::cloned(&self.fast),
116            subset: self.subset.clone(),
117        }
118    }
119}
120
121impl<'outer> RuleSetBuilder<'outer> {
122    pub fn new(db: &'outer mut Database) -> Self {
123        Self {
124            rule_set: Default::default(),
125            db,
126            header_cache: Default::default(),
127        }
128    }
129
130    /// Estimate the size of the subset of the table matching the given
131    /// constraint.
132    ///
133    /// This is a wrapper around the [`Database::estimate_size`] method.
134    pub fn estimate_size(&self, table: TableId, c: Option<Constraint>) -> usize {
135        self.db.estimate_size(table, c)
136    }
137
138    /// Add a rule to this rule set.
139    pub fn new_rule<'a>(&'a mut self) -> QueryBuilder<'outer, 'a> {
140        let instrs = with_pool_set(PoolSet::get);
141        QueryBuilder {
142            rsb: self,
143            instrs,
144            query: Query {
145                var_info: Default::default(),
146                atoms: Default::default(),
147                // start with an invalid ActionId
148                action: ActionId::new(u32::MAX),
149                plan_strategy: Default::default(),
150                fun_deps: Default::default(),
151                no_decomp: false,
152            },
153        }
154    }
155
156    fn reprocess_constraints(
157        &mut self,
158        table: TableId,
159        atom: AtomId,
160        constraints: &[Constraint],
161    ) -> Option<JoinHeader> {
162        let table_cache = self.header_cache.get_or_insert(table, HashMap::default);
163        if let Some(cached) = table_cache.get(constraints) {
164            return cached.as_ref().map(|cached| cached.header(atom));
165        }
166        let processed = self.db.process_constraints(table, constraints);
167        if !processed.slow.is_empty() {
168            panic!(
169                "Cached plans only support constraints with a fast pushdown. \
170                 Got: {constraints:?} for table {table:?}",
171            );
172        }
173        let cached = (processed.subset.size() != 0).then(|| CachedHeaderConstraints {
174            fast: processed.fast,
175            subset: processed.subset,
176        });
177        let header = cached.as_ref().map(|cached| cached.header(atom));
178        // Borrowed slice lookup above allocates a key only on a cache miss.
179        table_cache.insert(constraints.to_vec(), cached);
180        header
181    }
182
183    fn push_extra_constraints(
184        &mut self,
185        headers: &mut Vec<JoinHeader>,
186        atoms: &Arc<DenseIdMap<AtomId, Atom>>,
187        extra_constraints: &[(AtomId, Constraint)],
188    ) -> Option<()> {
189        for (atom_id, constraint) in extra_constraints {
190            let atom_info = atoms.get(*atom_id).expect("atom must exist in plan");
191            let table = atom_info.table;
192            headers.push(self.reprocess_constraints(
193                table,
194                *atom_id,
195                std::slice::from_ref(constraint),
196            )?);
197        }
198        Some(())
199    }
200
201    fn reprocess_existing_headers(
202        &mut self,
203        headers: &mut Vec<JoinHeader>,
204        atoms: &Arc<DenseIdMap<AtomId, Atom>>,
205        existing: &[JoinHeader],
206    ) -> Option<()> {
207        for JoinHeader {
208            atom, constraints, ..
209        } in existing
210        {
211            let atom_info = atoms.get(*atom).expect("atom must exist in plan");
212            let table = atom_info.table;
213            headers.push(self.reprocess_constraints(table, *atom, constraints)?);
214        }
215        Some(())
216    }
217
218    fn get_rule_with_extra_constraints(
219        &mut self,
220        cached: &CachedPlan,
221        action_id: ActionId,
222        extra_constraints: &[(AtomId, Constraint)],
223    ) -> Option<Plan> {
224        match &cached.plan {
225            Plan::SinglePlan(cached_plan) => {
226                let mut headers = vec![];
227                let stages = cached_plan.stages.clone();
228                self.push_extra_constraints(&mut headers, &cached_plan.atoms, extra_constraints)?;
229                self.reprocess_existing_headers(
230                    &mut headers,
231                    &cached_plan.atoms,
232                    &cached_plan.header,
233                )?;
234                Some(Plan::SinglePlan(SinglePlan {
235                    atoms: cached_plan.atoms.clone(),
236                    header: headers,
237                    stages,
238                    actions: action_id,
239                }))
240            }
241            Plan::DecomposedPlan(cached_plan) => {
242                let mut blocks = Vec::with_capacity(cached_plan.stages.blocks.len());
243                let mut headers = vec![];
244                self.push_extra_constraints(&mut headers, &cached_plan.atoms, extra_constraints)?;
245                self.reprocess_existing_headers(
246                    &mut headers,
247                    &cached_plan.atoms,
248                    &cached_plan.header,
249                )?;
250                for cached_block in cached_plan.stages.blocks.iter() {
251                    let stages = cached_block.0.clone();
252                    blocks.push((stages, cached_block.1.clone()));
253                }
254                let result_block = cached_plan.result_block.clone();
255                Some(Plan::DecomposedPlan(DecomposedPlan {
256                    atoms: cached_plan.atoms.clone(),
257                    header: headers,
258                    stages: JoinStageBlocks { blocks },
259                    actions: action_id,
260                    result_block,
261                }))
262            }
263        }
264    }
265
266    /// Add a rule to this rule set based on a previously cached plan, optionally
267    /// with additional constraints applied on top.
268    ///
269    /// Returns `None` if the query is provably empty given the current database
270    /// state (i.e. some constraint narrows a table to zero matching rows), in
271    /// which case no rule or action is allocated. Returns `Some(RuleId)` otherwise.
272    ///
273    /// The primary use-case is seminaive evaluation: an egglog rule is compiled
274    /// once into a [`CachedPlan`] and then added to a fresh [`RuleSet`] each
275    /// iteration with timestamp constraints (e.g. `GeConst` on the focus atom)
276    /// that select only new tuples. If no new tuples exist for an atom, the
277    /// `None` return allows the caller to skip that variant entirely.
278    pub fn add_rule_from_cached_plan(
279        &mut self,
280        cached: &CachedPlan,
281        extra_constraints: &[(AtomId, Constraint)],
282    ) -> Option<RuleId> {
283        // Peek at the action_id without allocating it yet, so we don't break
284        // the rules<->actions bijection if the query turns out to be empty.
285        let action_id = self.rule_set.actions.next_id();
286        let plan = self.get_rule_with_extra_constraints(cached, action_id, extra_constraints)?;
287        // The query is non-empty: now commit the action and the plan.
288        let actual_action_id = self.rule_set.actions.push(cached.actions.clone());
289        debug_assert_eq!(action_id, actual_action_id);
290        Some(
291            self.rule_set
292                .plans
293                .push((plan, cached.desc.clone(), cached.symbol_map.clone())),
294        )
295    }
296
297    /// Build the ruleset.
298    pub fn build(self) -> RuleSet {
299        self.rule_set
300    }
301}
302
303/// Builder for the "query" portion of the rule.
304///
305/// Queries specify scans or joins over the database that bind variables that
306/// are accessible to rules.
307pub struct QueryBuilder<'outer, 'a> {
308    rsb: &'a mut RuleSetBuilder<'outer>,
309    query: Query,
310    instrs: Pooled<Vec<Instr>>,
311}
312
313impl<'outer, 'a> QueryBuilder<'outer, 'a> {
314    /// Finish the query and start building the right-hand side of the rule.
315    pub fn build(self) -> RuleBuilder<'outer, 'a> {
316        RuleBuilder { qb: self }
317    }
318
319    /// Set the target plan strategy to use to execute this query.
320    pub fn set_plan_strategy(&mut self, strategy: PlanStrategy) {
321        self.query.plan_strategy = strategy;
322    }
323
324    /// If `true`, the query planner will skip tree-decomposition
325    /// for query decomposition and always use evaluate the query as a single bag.
326    pub fn set_no_decomp(&mut self, no_decomp: bool) {
327        self.query.no_decomp = no_decomp;
328    }
329
330    /// Create a new variable of the given type.
331    pub fn new_var(&mut self) -> Variable {
332        self.query.var_info.push(VarInfo {
333            occurrences: Default::default(),
334            used_in_rhs: false,
335            defined_in_rhs: false,
336            name: None,
337        })
338    }
339
340    pub fn new_var_named(&mut self, name: &str) -> Variable {
341        self.query.var_info.push(VarInfo {
342            occurrences: Default::default(),
343            used_in_rhs: false,
344            defined_in_rhs: false,
345            name: Some(name.into()),
346        })
347    }
348
349    fn mark_used<'b>(&mut self, entries: impl IntoIterator<Item = &'b QueryEntry>) {
350        for entry in entries {
351            if let QueryEntry::Var(v) = entry {
352                self.query.var_info[*v].used_in_rhs = true;
353            }
354        }
355    }
356
357    fn mark_defined(&mut self, entry: &QueryEntry) {
358        // TODO: use some of this information in query planning, e.g. dedup at match time.
359        if let QueryEntry::Var(v) = entry {
360            self.query.var_info[*v].defined_in_rhs = true;
361        }
362    }
363
364    /// Add the given atom to the query, with the given variables and constraints.
365    ///
366    /// NB: it is possible to constrain two non-equal variables to be equal
367    /// given this setup. Doing this will not cause any problems but
368    /// nevertheless is not recommended.
369    ///
370    /// The returned `AtomId` can be used to refer to this atom when adding constraints in
371    /// [`RuleSetBuilder::add_rule_from_cached_plan`].
372    ///
373    /// # Panics
374    /// Like most methods that take a [`TableId`], this method will panic if the
375    /// given table is not declared in the corresponding database.
376    pub fn add_atom<'b>(
377        &mut self,
378        table_id: TableId,
379        vars: &[QueryEntry],
380        cs: impl IntoIterator<Item = &'b Constraint>,
381    ) -> Result<AtomId, QueryError> {
382        let info = &self.rsb.db.tables[table_id];
383        let arity = info.spec.arity();
384        let check_constraint = |c: &Constraint| {
385            let process_col = |col: &ColumnId| -> Result<(), QueryError> {
386                if col.index() >= arity {
387                    Err(QueryError::InvalidConstraint {
388                        constraint: c.clone(),
389                        column: col.index(),
390                        table: table_id,
391                        arity,
392                    })
393                } else {
394                    Ok(())
395                }
396            };
397            match c {
398                Constraint::Eq { l_col, r_col } => {
399                    process_col(l_col)?;
400                    process_col(r_col)
401                }
402                Constraint::EqConst { col, .. }
403                | Constraint::LtConst { col, .. }
404                | Constraint::GtConst { col, .. }
405                | Constraint::LeConst { col, .. }
406                | Constraint::GeConst { col, .. } => process_col(col),
407            }
408        };
409        if arity != vars.len() {
410            return Err(QueryError::BadArity {
411                table: table_id,
412                expected: arity,
413                got: vars.len(),
414            });
415        }
416        let cs = Vec::from_iter(
417            cs.into_iter()
418                .cloned()
419                .chain(vars.iter().enumerate().filter_map(|(i, qe)| match qe {
420                    QueryEntry::Var(_) => None,
421                    QueryEntry::Const(c) => Some(Constraint::EqConst {
422                        col: ColumnId::from_usize(i),
423                        val: *c,
424                    }),
425                })),
426        );
427        cs.iter().try_fold((), |_, c| check_constraint(c))?;
428        let processed = self.rsb.db.process_constraints(table_id, &cs);
429        let mut atom = Atom {
430            table: table_id,
431            var_columns: Default::default(),
432            constraints: processed,
433        };
434        let next_atom = AtomId::from_usize(self.query.atoms.n_ids());
435        let mut subatoms = HashMap::<Variable, SubAtom>::default();
436        for (i, qe) in vars.iter().enumerate() {
437            let var = match qe {
438                QueryEntry::Var(var) => *var,
439                QueryEntry::Const(_) => {
440                    continue;
441                }
442            };
443            if var == Variable::placeholder() {
444                continue;
445            }
446            let col = ColumnId::from_usize(i);
447            if let Some(prev) = atom.var_columns.insert(var, col) {
448                atom.constraints.slow.push(Constraint::Eq {
449                    l_col: col,
450                    r_col: prev,
451                })
452            };
453            subatoms
454                .entry(var)
455                .or_insert_with(|| SubAtom::new(next_atom))
456                .vars
457                .push(col);
458        }
459        for (var, subatom) in subatoms {
460            self.query
461                .var_info
462                .get_mut(var)
463                .expect("all variables must be bound in current query")
464                .occurrences
465                .push(subatom);
466        }
467
468        // Add functional dependencies for this atom.
469        let get_var = |qe: &QueryEntry| match qe {
470            QueryEntry::Var(v) => Some(*v),
471            QueryEntry::Const(_) => None,
472        };
473        let antecedent = vars[..info.spec().n_keys]
474            .iter()
475            .filter_map(get_var)
476            .collect::<Vec<_>>();
477        let consequent = vars[info.spec().n_keys..]
478            .iter()
479            .filter_map(get_var)
480            .collect::<Vec<_>>();
481        self.query.fun_deps.add_dependency(antecedent, consequent);
482
483        Ok(self.query.atoms.push(atom))
484    }
485}
486
487#[derive(Debug, Error)]
488pub enum QueryError {
489    #[error("table {table:?} has {expected:?} keys but got {got:?}")]
490    KeyArityMismatch {
491        table: TableId,
492        expected: usize,
493        got: usize,
494    },
495    #[error("table {table:?} has {expected:?} columns but got {got:?}")]
496    TableArityMismatch {
497        table: TableId,
498        expected: usize,
499        got: usize,
500    },
501
502    #[error(
503        "counter used in column {column_id:?} of table {table:?}, which is declared as a base value"
504    )]
505    CounterUsedInBaseColumn {
506        table: TableId,
507        column_id: ColumnId,
508        base: BaseValueId,
509    },
510
511    #[error("attempt to compare two groups of values, one of length {l}, another of length {r}")]
512    MultiComparisonMismatch { l: usize, r: usize },
513
514    #[error("table {table:?} expected {expected:?} columns but got {got:?}")]
515    BadArity {
516        table: TableId,
517        expected: usize,
518        got: usize,
519    },
520
521    #[error("expected {expected:?} columns in schema but got {got:?}")]
522    InvalidSchema { expected: usize, got: usize },
523
524    #[error(
525        "constraint {constraint:?} on table {table:?} references column {column:?}, but the table has arity {arity:?}"
526    )]
527    InvalidConstraint {
528        constraint: Constraint,
529        column: usize,
530        table: TableId,
531        arity: usize,
532    },
533}
534
535/// Builder for the "action" portion of the rule.
536///
537/// Rules can refer to the variables bound in their query to modify the database.
538pub struct RuleBuilder<'outer, 'a> {
539    qb: QueryBuilder<'outer, 'a>,
540}
541
542impl RuleBuilder<'_, '_> {
543    fn table_info(&self, table: TableId) -> &TableInfo {
544        self.qb.rsb.db.get_table_info(table)
545    }
546
547    /// Build the finished query.
548    pub fn build(self) -> RuleId {
549        self.build_with_description("")
550    }
551
552    fn build_symbol_map(&self) -> SymbolMap {
553        let var_info = &self.qb.query.var_info;
554        SymbolMap {
555            atoms: self
556                .qb
557                .query
558                .atoms
559                .iter()
560                .filter_map(|(id, atom)| {
561                    let name = self.table_info(atom.table).name.clone();
562                    name.map(|name| (id, name))
563                })
564                .collect(),
565            vars: var_info
566                .iter()
567                .filter_map(|(id, info)| info.name.as_ref().map(|name| (id, name.clone())))
568                .collect(),
569        }
570    }
571
572    pub fn build_with_description(mut self, desc: impl Into<String>) -> RuleId {
573        let var_info = &self.qb.query.var_info;
574        let symbol_map = self.build_symbol_map();
575        // Generate an id for our actions and slot them in.
576        let used_vars = SmallVec::from_iter(var_info.iter().filter_map(|(v, info)| {
577            if info.used_in_rhs && !info.defined_in_rhs {
578                Some(v)
579            } else {
580                None
581            }
582        }));
583        let action_id = self.qb.rsb.rule_set.actions.push(ActionInfo {
584            instrs: Arc::new(self.qb.instrs),
585            used_vars,
586        });
587        self.qb.query.action = action_id;
588        // Plan the query
589        let plan = self.qb.rsb.db.plan_query(self.qb.query);
590        let desc: String = desc.into();
591        // Add it to the ruleset.
592        self.qb
593            .rsb
594            .rule_set
595            .plans
596            .push((plan, desc.into(), symbol_map))
597    }
598
599    /// Return a variable containing the result of reading the specified counter.
600    pub fn read_counter(&mut self, counter: CounterId) -> Variable {
601        let dst = self.qb.new_var();
602        self.qb.instrs.push(Instr::ReadCounter { counter, dst });
603        self.qb.mark_defined(&dst.into());
604        dst
605    }
606
607    /// Return a variable containing the result of looking up the specified
608    /// column from the row corresponding to given keys in the given
609    /// table.
610    ///
611    /// If the key does not currently have a mapping in the table, the values
612    /// specified by `default_vals` will be inserted.
613    pub fn lookup_or_insert(
614        &mut self,
615        table: TableId,
616        args: &[QueryEntry],
617        default_vals: &[WriteVal],
618        dst_col: ColumnId,
619    ) -> Result<Variable, QueryError> {
620        let table_info = self.table_info(table);
621        self.validate_keys(table, table_info, args)?;
622        self.validate_vals(table, table_info, default_vals.iter())?;
623        let res = self.qb.new_var();
624        self.qb.instrs.push(Instr::LookupOrInsertDefault {
625            table,
626            args: args.to_vec(),
627            default: default_vals.to_vec(),
628            dst_col,
629            dst_var: res,
630        });
631        self.qb.mark_used(args);
632        self.qb
633            .mark_used(default_vals.iter().filter_map(|x| match x {
634                WriteVal::QueryEntry(qe) => Some(qe),
635                WriteVal::IncCounter(_) | WriteVal::CurrentVal(_) => None,
636            }));
637        self.qb.mark_defined(&res.into());
638        Ok(res)
639    }
640
641    /// Return a variable containing the result of looking up the specified
642    /// column from the row corresponding to given keys in the given
643    /// table.
644    ///
645    /// If the key does not currently have a mapping in the table, the variable
646    /// takes the value of `default`.
647    pub fn lookup_with_default(
648        &mut self,
649        table: TableId,
650        args: &[QueryEntry],
651        default: QueryEntry,
652        dst_col: ColumnId,
653    ) -> Result<Variable, QueryError> {
654        let table_info = self.table_info(table);
655        self.validate_keys(table, table_info, args)?;
656        let res = self.qb.new_var();
657        self.qb.instrs.push(Instr::LookupWithDefault {
658            table,
659            args: args.to_vec(),
660            dst_col,
661            dst_var: res,
662            default,
663        });
664        self.qb.mark_used(args);
665        self.qb.mark_used(&[default]);
666        self.qb.mark_defined(&res.into());
667        Ok(res)
668    }
669
670    /// Return a variable containing the result of looking up the specified
671    /// column from the row corresponding to given keys in the given
672    /// table.
673    ///
674    /// If the key does not currently have a mapping in the table, execution of
675    /// the rule is halted.
676    pub fn lookup(
677        &mut self,
678        table: TableId,
679        args: &[QueryEntry],
680        dst_col: ColumnId,
681    ) -> Result<Variable, QueryError> {
682        let table_info = self.table_info(table);
683        self.validate_keys(table, table_info, args)?;
684        let res = self.qb.new_var();
685        self.qb.instrs.push(Instr::Lookup {
686            table,
687            args: args.to_vec(),
688            dst_col,
689            dst_var: res,
690        });
691        self.qb.mark_used(args);
692        self.qb.mark_defined(&res.into());
693        Ok(res)
694    }
695
696    /// Insert the specified values into the given table.
697    pub fn insert(&mut self, table: TableId, vals: &[QueryEntry]) -> Result<(), QueryError> {
698        let table_info = self.table_info(table);
699        self.validate_row(table, table_info, vals)?;
700        self.qb.instrs.push(Instr::Insert {
701            table,
702            vals: vals.to_vec(),
703        });
704        self.qb.mark_used(vals);
705        Ok(())
706    }
707
708    /// Insert the specified values into the given table if `l` and `r` are equal.
709    pub fn insert_if_eq(
710        &mut self,
711        table: TableId,
712        l: QueryEntry,
713        r: QueryEntry,
714        vals: &[QueryEntry],
715    ) -> Result<(), QueryError> {
716        let table_info = self.table_info(table);
717        self.validate_row(table, table_info, vals)?;
718        self.qb.instrs.push(Instr::InsertIfEq {
719            table,
720            l,
721            r,
722            vals: vals.to_vec(),
723        });
724        self.qb
725            .mark_used(vals.iter().chain(once(&l)).chain(once(&r)));
726        Ok(())
727    }
728
729    /// Remove the specified entry from the given table, if it is there.
730    pub fn remove(&mut self, table: TableId, args: &[QueryEntry]) -> Result<(), QueryError> {
731        let table_info = self.table_info(table);
732        self.validate_keys(table, table_info, args)?;
733        self.qb.instrs.push(Instr::Remove {
734            table,
735            args: args.to_vec(),
736        });
737        self.qb.mark_used(args);
738        Ok(())
739    }
740
741    /// Apply the given external function to the specified arguments.
742    pub fn call_external(
743        &mut self,
744        func: ExternalFunctionId,
745        args: &[QueryEntry],
746    ) -> Result<Variable, QueryError> {
747        let res = self.qb.new_var();
748        self.qb.instrs.push(Instr::External {
749            func,
750            args: args.to_vec(),
751            dst: res,
752        });
753        self.qb.mark_used(args);
754        self.qb.mark_defined(&res.into());
755        Ok(res)
756    }
757
758    /// Look up the given key in the given table. If the lookup fails, then call the given external
759    /// function with the given arguments. Bind the result to the returned variable. If the
760    /// external function returns None (and the lookup fails) then the execution of the rule halts.
761    pub fn lookup_with_fallback(
762        &mut self,
763        table: TableId,
764        key: &[QueryEntry],
765        dst_col: ColumnId,
766        func: ExternalFunctionId,
767        func_args: &[QueryEntry],
768    ) -> Result<Variable, QueryError> {
769        let table_info = self.table_info(table);
770        self.validate_keys(table, table_info, key)?;
771        let res = self.qb.new_var();
772        self.qb.instrs.push(Instr::LookupWithFallback {
773            table,
774            table_key: key.to_vec(),
775            func,
776            func_args: func_args.to_vec(),
777            dst_var: res,
778            dst_col,
779        });
780        self.qb.mark_used(key);
781        self.qb.mark_used(func_args);
782        self.qb.mark_defined(&res.into());
783        Ok(res)
784    }
785
786    pub fn call_external_with_fallback(
787        &mut self,
788        f1: ExternalFunctionId,
789        args1: &[QueryEntry],
790        f2: ExternalFunctionId,
791        args2: &[QueryEntry],
792    ) -> Result<Variable, QueryError> {
793        let res = self.qb.new_var();
794        self.qb.instrs.push(Instr::ExternalWithFallback {
795            f1,
796            args1: args1.to_vec(),
797            f2,
798            args2: args2.to_vec(),
799            dst: res,
800        });
801        self.qb.mark_used(args1);
802        self.qb.mark_used(args2);
803        self.qb.mark_defined(&res.into());
804        Ok(res)
805    }
806
807    /// Continue execution iff the two arguments are equal.
808    pub fn assert_eq(&mut self, l: QueryEntry, r: QueryEntry) {
809        self.qb.instrs.push(Instr::AssertEq(l, r));
810        self.qb.mark_used(&[l, r]);
811    }
812
813    /// Continue execution iff the two arguments are not equal.
814    pub fn assert_ne(&mut self, l: QueryEntry, r: QueryEntry) -> Result<(), QueryError> {
815        self.qb.instrs.push(Instr::AssertNe(l, r));
816        self.qb.mark_used(&[l, r]);
817        Ok(())
818    }
819
820    /// Continue execution iff there is some `i` such that `l[i] != r[i]`.
821    ///
822    /// This is useful when doing egglog-style rebuilding.
823    pub fn assert_any_ne(&mut self, l: &[QueryEntry], r: &[QueryEntry]) -> Result<(), QueryError> {
824        if l.len() != r.len() {
825            return Err(QueryError::MultiComparisonMismatch {
826                l: l.len(),
827                r: r.len(),
828            });
829        }
830
831        let mut ops = Vec::with_capacity(l.len() + r.len());
832        ops.extend_from_slice(l);
833        ops.extend_from_slice(r);
834        self.qb.instrs.push(Instr::AssertAnyNe {
835            ops,
836            divider: l.len(),
837        });
838        self.qb.mark_used(l);
839        self.qb.mark_used(r);
840        Ok(())
841    }
842
843    fn validate_row(
844        &self,
845        table: TableId,
846        info: &TableInfo,
847        vals: &[QueryEntry],
848    ) -> Result<(), QueryError> {
849        if vals.len() != info.spec.arity() {
850            Err(QueryError::TableArityMismatch {
851                table,
852                expected: info.spec.arity(),
853                got: vals.len(),
854            })
855        } else {
856            Ok(())
857        }
858    }
859
860    fn validate_keys(
861        &self,
862        table: TableId,
863        info: &TableInfo,
864        keys: &[QueryEntry],
865    ) -> Result<(), QueryError> {
866        if keys.len() != info.spec.n_keys {
867            Err(QueryError::KeyArityMismatch {
868                table,
869                expected: info.spec.n_keys,
870                got: keys.len(),
871            })
872        } else {
873            Ok(())
874        }
875    }
876
877    fn validate_vals<'b>(
878        &self,
879        table: TableId,
880        info: &TableInfo,
881        vals: impl Iterator<Item = &'b WriteVal>,
882    ) -> Result<(), QueryError> {
883        for (i, _) in vals.enumerate() {
884            let col = i + info.spec.n_keys;
885            if col >= info.spec.arity() {
886                return Err(QueryError::TableArityMismatch {
887                    table,
888                    expected: info.spec.arity(),
889                    got: col,
890                });
891            }
892        }
893        Ok(())
894    }
895}
896
897#[derive(Debug, Clone)]
898pub(crate) struct Atom {
899    pub(crate) table: TableId,
900    pub(crate) var_columns: VarColumnMap,
901    /// These constraints are an initial take at processing "fast" constraints as well as a
902    /// potential list of "slow" constraints.
903    ///
904    /// Fast constraints get re-computed when queries are executed. In particular, this makes it
905    /// possible to cache plans and add new fast constraints to them without re-planning.
906    pub(crate) constraints: ProcessedConstraints,
907}
908
909impl Atom {
910    pub(crate) fn vars(&self) -> impl Iterator<Item = Variable> + '_ {
911        self.var_columns.vars()
912    }
913
914    pub(crate) fn get_var(&self, col: ColumnId) -> Option<Variable> {
915        self.var_columns.get_var(col)
916    }
917
918    pub(crate) fn get_col(&self, var: Variable) -> Option<ColumnId> {
919        self.var_columns.get_col(var)
920    }
921}
922
923#[derive(Clone, Default)]
924pub(crate) struct VarColumnMap {
925    var_to_column: DenseIdMap<Variable, ColumnId>,
926    column_to_var: DenseIdMap<ColumnId, Variable>,
927}
928
929impl std::fmt::Debug for VarColumnMap {
930    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
931        let mut entries: Vec<_> = self.column_to_var.iter().collect();
932        entries.sort_by_key(|(col, _)| col.index());
933
934        f.write_str("VarColumnMap(")?;
935        for (i, (col, var)) in entries.iter().enumerate() {
936            if i > 0 {
937                f.write_str(", ")?;
938            }
939            write!(f, "{col:?} -> {var:?}")?;
940        }
941        f.write_str(")")
942    }
943}
944
945impl VarColumnMap {
946    pub(crate) fn insert(&mut self, var: Variable, col: ColumnId) -> Option<ColumnId> {
947        let prev = self.var_to_column.insert(var, col);
948        self.column_to_var.insert(col, var);
949        prev
950    }
951
952    pub(crate) fn get_col(&self, var: Variable) -> Option<ColumnId> {
953        self.var_to_column.get(var).copied()
954    }
955
956    pub(crate) fn get_var(&self, col: ColumnId) -> Option<Variable> {
957        self.column_to_var.get(col).copied()
958    }
959
960    pub(crate) fn iter(&self) -> impl Iterator<Item = (ColumnId, Variable)> + '_ {
961        self.column_to_var.iter().map(|(col, var)| (col, *var))
962    }
963
964    pub(crate) fn vars(&self) -> impl Iterator<Item = Variable> + '_ {
965        self.iter().map(|(_, var)| var)
966    }
967
968    pub(crate) fn is_empty(&self) -> bool {
969        self.var_to_column.len() == 0
970    }
971}
972
973/// A functional dependency inferencer.
974///
975/// A functional dependency (x, y, ...) -> (u, v, ...) means that if we know
976/// the values of x, y, ..., then we can determine u, v, ...
977///
978/// This data structure can compute the closure of a set of variables under
979/// a set of functional dependencies.
980#[derive(Clone, Default)]
981pub(crate) struct FunDeps {
982    /// List of functional dependencies (antecedent -> consequent)
983    dependencies: Vec<(Vec<Variable>, Vec<Variable>)>,
984}
985
986impl FunDeps {
987    /// Add a functional dependency: antecedent -> consequent.
988    pub fn add_dependency(&mut self, antecedent: Vec<Variable>, consequent: Vec<Variable>) {
989        // Don't add trivial dependencies.
990        if !antecedent.is_empty() {
991            self.dependencies.push((antecedent, consequent));
992        }
993    }
994
995    /// Returns all variables that can be determined from the input variables
996    /// using the functional dependencies.
997    pub fn closure(
998        &self,
999        variables: impl IntoIterator<Item = Variable>,
1000    ) -> DenseIdMap<Variable, ()> {
1001        let mut result: DenseIdMap<Variable, ()> =
1002            DenseIdMap::from_iter(variables.into_iter().map(|v| (v, ())));
1003        let mut changed = true;
1004
1005        while changed {
1006            changed = false;
1007            for (antecedent, consequent) in &self.dependencies {
1008                // If all variables in the antecedent are in the result,
1009                // add all variables in the consequent.
1010                if antecedent.iter().all(|v| result.contains_key(*v)) {
1011                    for v in consequent {
1012                        if !result.contains_key(*v) {
1013                            result.insert(*v, ());
1014                            changed = true;
1015                        }
1016                    }
1017                }
1018            }
1019        }
1020
1021        result
1022    }
1023}
1024
1025impl std::fmt::Debug for FunDeps {
1026    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1027        use std::fmt::Write;
1028
1029        let mut deps = String::new();
1030
1031        for (i, (ant, cons)) in self.dependencies.iter().enumerate() {
1032            if i > 0 {
1033                deps.push_str("; ");
1034            }
1035
1036            deps.push('{');
1037            for (j, v) in ant.iter().enumerate() {
1038                if j > 0 {
1039                    deps.push_str(", ");
1040                }
1041                write!(&mut deps, "{v:?}")?;
1042            }
1043            deps.push('}');
1044
1045            deps.push_str(" -> ");
1046
1047            deps.push('{');
1048            for (j, v) in cons.iter().enumerate() {
1049                if j > 0 {
1050                    deps.push_str(", ");
1051                }
1052                write!(&mut deps, "{v:?}")?;
1053            }
1054            deps.push('}');
1055        }
1056
1057        write!(f, "FunDeps {{ {deps} }}")
1058    }
1059}
1060
1061pub(crate) struct Query {
1062    pub(crate) var_info: DenseIdMap<Variable, VarInfo>,
1063    pub(crate) atoms: DenseIdMap<AtomId, Atom>,
1064    pub(crate) action: ActionId,
1065    pub(crate) plan_strategy: PlanStrategy,
1066    pub(crate) fun_deps: FunDeps,
1067    /// If `true`, skip tree-decomposition during query planning and
1068    /// always use the single-bag fast path in
1069    /// [`crate::free_join::plan::tree_decompose_and_plan`]. Set via
1070    /// [`QueryBuilder::set_no_decomp`].
1071    pub(crate) no_decomp: bool,
1072}