crates/kleene-datalog/src/lib.rs
//! Datalog over X.gar graphs, built in Rust: a client of kleene-plan.
//!
//! The rules are written as typed Rust values and lowered onto a [`kleene_plan::Plan`];
//! the plan's planner and engine run them. This crate holds the typed front only.
//!
//! The same rule two ways, the builder and [`datalog!`] (the grammar is there):
//!
//! ```
//! use kleene_datalog::{Program, datalog};
//! let mut p = Program::new();
//! let entry = p.input::<1>("entry");
//! let calls = p.input::<2>("calls");
//! let reach = p.derived::<1>("reach");
//! let (f, g) = (p.var("F"), p.var("G"));
//! p.rule(reach.at([f]), [entry.at([f])]).unwrap();
//! datalog!(&mut p => reach(G) :- reach(F), calls(F, G).).unwrap();
//! assert_eq!(p.rules().len(), 2);
//! assert!(kleene_datalog::plan(&p).is_ok());
//! ```
//!
//! | Part | Here |
//! |---|---|
//! | Rules | [`Program`]: relations with their arity in the type ([`Rel<N>`]), variables, rules as Rust values (no parser at run time); conditions [`ne`], [`lt`], [`le`], [`gt`], [`ge`], [`eq`], [`within`] (`lo <= x < hi`), each side a term or an [`Expr`] (`F & 4 != 0`); computed values [`compute`] (`O = LO + I`: arithmetic and bit operators, the value of its variable's type, no row where it does not fit an unsigned one); [`is_null`], [`is_not_null`], string tests [`starts_with`], [`ends_with`], [`contains`]; `!atom` for negation; [`Program::aggregate`] for count, min / max by a key tuple ("first"), exactly one; [`Program::fold`] for sum and avg; [`Program::rounds`] for count and negation inside recursion (inflationary rounds) |
//! | Rules as text | [`datalog!`]: the same rules written as Datalog in Rust (`reach(G) :- reach(F), calls(F, G).`), turned into the builder's calls at build time; it makes a new program with its relations or adds to one in hand, beside builder rules, on its `Rel<N>` handles |
//! | Inputs | [`Inputs`]: by name from a [`Catalog`] (a set's schema, read by kleene-gar's `GarGraph::catalog`: [`Program::input_from`] declares `L`, `E`, `L.k`, `E.k` with the catalog's types, [`Program::input_or_empty`] one that is empty where the set lacks it, [`Program::schema`] the set's labels, edge labels and columns as relations a rule reads, [`Inputs::bind`] gives each its source); facts in hand, columns of a DataFusion table (an X.gar table from kleene-gar), a two-column relation as a graph shared with no copy, or an [`External`] (index lookups, Rust fact producers), each checked against its relation's arity |
//! | Types | [`Program::input_typed`] / [`Program::derived_typed`] with a [`Type`] per column (strings, signed integers, floats, booleans, nulls); constants [`Program::str`], [`Term::int`], [`Term::float`], [`Term::bool`]; [`is_null`], [`is_not_null`]; Arrow string, integer, float and boolean columns in; [`Output::arrow`] gives Arrow arrays of the column types, [`Output::datums`] typed rows, [`Output::render`] typed proofs |
//! | Index choice | a rule that filters an input with an index ([`Inputs::index`], or the catalog's through [`Inputs::bind`]: a property's range or name index, a label's id block) by constants finds its ids by the index ([`Engine::index_choice`], on by default): `young(N) :- person(N), person.age(N, A), A < 30` needs no index atom; a lookup written by hand (`idx(0, 29, N)` in a body) is asked once, the same plan |
//! | Output | [`Output::ordered`]: a relation's rows through the core's output operator ([`Order`]: keys ([`OrderKey`]) rising or falling, nulls first or last ([`Nulls`]), an offset, a limit), typed |
//! | Several aggregates | [`Program::aggregate`] with [`Aggregate::many`]: count, sum, mean, least and greatest value ([`Reduce`]) of each group in one rule, nulls skipped (`stats(W, N, S, Lo) :- N = count (A), S = sum (A), Lo = min (A) by (W): sale(W, A)`) |
//! | The position in an order | [`Program::aggregate`] with [`Aggregate::rank`]: `pos(G, K, N) :- N = rank(K) by (G): item(G, K).`, N the number of distinct keys of the group before K, from 0 |
//! | A number for each distinct set | [`Program::sets`] declares a table of sets (`sets state/2 limit 1000.`), [`Program::aggregate`] with [`Aggregate::set_number`] numbers each group's set in it (`step(P, A, N) :- N = set(Y) by (P, A) in state: ..`): equal sets one number, also across rules, in rounds inside recursion, the same numbers on every run; over the limit a run stops with [`DatalogError::SetLimit`]; [`Program::state_machine`] adds the whole subset construction of a graph with labels (states, steps, starts) |
//! | Graph procedures | [`Program::procedure`]: a relation given by a graph kernel over an edge relation ([`Procedure`]: PageRank, components, shortest paths, betweenness, triangles, ...), in the edges' ids however far apart |
//! | Id relations | [`IdShift`] (`(row, id)` of a vertex table by arithmetic), [`IdRanges`] (the ids of id blocks within ranges, or their rows), [`NameHits`] (the ids a name index gives for some strings), each an external relation for rules |
//! | Whole values | [`Engine::read_entities`]: every property of some nodes ([`NodeAsk`]) and edges ([`EdgeAsk`]) and which labels hold them, read for the ids asked alone ([`Entities`]) |
//! | Edge tests of a walk | [`Program::edge_filter`]: the edges that pass every [`EdgeTest`], a relation a walk reads |
//! | Null marks, union, stages | [`NullMark`] / [`Marked`]: rows with their null cells where an optional part's flag is 0, `UNION ALL` and `UNION` over them (a null kept apart from every value); [`Inputs::datums`]: another run's typed rows as an input, counted or not |
//! | Run | [`Engine`]: [`kleene_plan::Engine`] on the program's plan; [`Output`] gives facts and proofs by typed relation; [`Engine::continue_from`] runs it again on inputs that gained rows, [`Engine::continue_with`] on inputs that gained and lost rows, from an earlier output (the same facts and proofs as from scratch) |
//! | In kleene-plan | the planner ([`plan`]: strata; reach as a BFS on kleene-graph, closure as masked products on kleene-sparse, an (entry, vertex) relation grown along labelled edges whose labels hold the entry (`r(E, T) :- r(E, S), edge(S, T, L), has(L, E)`) as one entry-bitmask walk (kleene-graph label_reach), the rest as column kernels: hash joins on packed keys, anti-joins, sorted groups), semi-naive rounds, stratified negation and aggregates (ties broken by a total order, the same answer at any thread count), external relations asked set at a time, values ([`Value`] = `u64`, [`Column`] widens and never cuts), the why of every fact ([`Proof`]), [`Trace`] |
mod engine;
mod macros;
mod program;
pub use engine::{Engine, Inputs, Output};
pub use kleene_plan::PlanError as DatalogError;
pub use kleene_plan::{
Agg, Aggregate, Atom, BinOp, Catalog, Cmp, Column, Compute, Cond, Constant, DEFAULT_SET_LIMIT,
Datum, Dict, EdgeAsk, EdgeTest, Entities, Expr, External, Facts, Fold, FoldOp, Func, How,
IdRanges, IdShift, Index, List, ListId, ListMember, Literal, Marked, Member, NULL, NameHits,
NameIndex, NoTrace, NodeAsk, NullMark, Nulls, Order, OrderKey, Part, Procedure, Producer,
Proof, Reduce, ReduceOp, RelId, RelInfo, RelKind, Report, Rule, RuleId, Side, Source, Stratum,
StratumReport, Term, Test, TextOp, Trace, Type, UnOp, Value, Var, Way, instantiate,
};
pub use program::{
Machine, Program, Rel, Schema, compare, compute, contains, ends_with, eq, ge, gt, is_not_null,
is_null, le, lt, ne, not_one_of, one_of, plan, starts_with, text, within,
};
#[doc = include_str!("datalog_macro.md")]
#[doc(inline)]
pub use kleene_datalog_macros::datalog;
/// What the expansion of [`datalog!`] calls; not an API of its own.
#[doc(hidden)]
pub mod __private {
pub use crate::macros::{
IntoMember, IntoMembers, IntoTerm, catalog, konst, list, member, members, term,
};
}
/// The result of a fallible operation of this crate.
pub type Result<T> = std::result::Result<T, DatalogError>;
/// The README's example, run as a doctest.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;