Expand description
§kmb-query: SQL query layer for Kimberlite projections
This crate provides a minimal SQL query engine for compliance lookups against the projection store.
§SQL Subset
Supported SQL features:
-
SELECTwith column list or* -
FROMsingle table orJOIN(INNER,LEFT,RIGHT,FULL OUTER,CROSS, withONorUSING(...)clauses) -
WHEREwith comparison predicates (=,<,>,<=,>=,IN) -
IN (SELECT),NOT IN (SELECT),EXISTS,NOT EXISTS— both uncorrelated (pre-execute fast path) and correlated (semi-join decorrelation or nested-loop fallback; seedocs/reference/sql/correlated-subqueries.md) -
ORDER BY(ascending/descending) -
LIMITandOFFSET— literal or$Nparameter -
GROUP BYwith aggregates (COUNT,SUM,AVG,MIN,MAX) -
Aggregate
FILTER (WHERE ...)clauses, independent per aggregate -
HAVINGwith aggregate filtering -
UNION/UNION ALL/INTERSECT/INTERSECT ALL/EXCEPT/EXCEPT ALL -
DISTINCT -
JSON operators
->,->>,@>in WHERE clauses -
CASE(searched and simple form) -
WITH(Common Table Expressions / CTEs), includingWITH RECURSIVEvia iterative fixed-point evaluation (depth cap 1000) -
Subqueries in FROM and JOIN (
SELECT * FROM (SELECT ...) AS t) -
Window functions (
OVER,PARTITION BY,ROW_NUMBER,RANK,DENSE_RANK,LAG,LEAD,FIRST_VALUE,LAST_VALUE) -
ALTER TABLE(ADD COLUMN, DROP COLUMN) — parser only; kernel execution pending -
Parameterized queries (
$1,$2, …) in WHERE, LIMIT, OFFSET, and DML values -
Scalar functions in SELECT projection and WHERE predicates:
UPPER,LOWER,LENGTH,TRIM,CONCAT,||,ABS,ROUND,CEIL/CEILING,FLOOR,COALESCE,NULLIF,CAST -
ILIKE,NOT LIKE,NOT ILIKEpattern matching -
NOT IN (list),NOT BETWEEN low AND high
Not yet supported:
- Scalar subquery
WHERE col = (SELECT ...),ANY,ALL,SOME - Clock-dependent functions (
NOW(),CURRENT_DATE,EXTRACT,DATE_TRUNC) — deferred pending a clock-threading decision MOD,POWER,SQRT,SUBSTRING— deferred
§Usage
use kimberlite_query::{QueryEngine, Schema, SchemaBuilder, ColumnDef, DataType, Value};
use kimberlite_store::{BTreeStore, TableId};
// Define schema
let schema = SchemaBuilder::new()
.table(
"users",
TableId::new(1),
vec![
ColumnDef::new("id", DataType::BigInt).not_null(),
ColumnDef::new("name", DataType::Text).not_null(),
],
vec!["id".into()],
)
.build();
// Create engine
let engine = QueryEngine::new(schema);
// Execute query
let mut store = BTreeStore::open("data/projections")?;
let result = engine.query(&mut store, "SELECT * FROM users WHERE id = $1", &[Value::BigInt(42)])?;§Point-in-Time Queries
For compliance, you can query at a specific log position:
let result = engine.query_at(
&mut store,
"SELECT * FROM users WHERE id = 1",
&[],
Offset::new(1000), // Query state as of log position 1000
)?;§Scalar expressions (v0.5.1)
The parser accepts scalar functions in SELECT projection and WHERE
predicates. Each of these queries parses cleanly and produces a
ParsedStatement::Select with either a ScalarCmp predicate or
entries in scalar_projections:
use kimberlite_query::{parse_statement, ParsedStatement, Predicate};
// WHERE col NOT IN (list) — mirror of IN, v0.5.1.
let s = parse_statement("SELECT id FROM t WHERE x NOT IN (1, 2, 3)").unwrap();
let ParsedStatement::Select(sel) = s else { panic!() };
assert!(matches!(sel.predicates[0], Predicate::NotIn(_, _)));
// WHERE UPPER(name) = 'ALICE' — scalar LHS routes to ScalarCmp.
let s = parse_statement("SELECT id FROM t WHERE UPPER(name) = 'ALICE'").unwrap();
let ParsedStatement::Select(sel) = s else { panic!() };
assert!(matches!(sel.predicates[0], Predicate::ScalarCmp { .. }));
// SELECT col AS alias — alias preserved end-to-end.
let s = parse_statement("SELECT name AS display FROM t").unwrap();
let ParsedStatement::Select(sel) = s else { panic!() };
let aliases = sel.column_aliases.as_ref().unwrap();
assert_eq!(aliases[0].as_deref(), Some("display"));
// SELECT CAST(x AS INTEGER) — lands in scalar_projections with a
// synthesised output column name.
let s = parse_statement("SELECT CAST(x AS INTEGER) FROM t").unwrap();
let ParsedStatement::Select(sel) = s else { panic!() };
assert_eq!(sel.scalar_projections.len(), 1);
assert_eq!(sel.scalar_projections[0].output_name.as_str(), "cast");Re-exports§
pub use expression::EvalContext;pub use expression::ScalarExpr;pub use expression::evaluate;
Modules§
- correlated
- Correlated subquery support (v0.6.0).
- depth_
check - Pre-parse input validation that rejects deeply-nested SQL to prevent
DoS attacks that exploit super-linear behavior in the upstream SQL
parser on expressions like
(NOT(NOT(NOT(...)))). - dml_
planner - AUDIT-2026-04 S3.1 — translate parsed DML AST into the wire-event
payloads that
kimberlite-kernel’sCommand::Insert/Command::Update/Command::Deletecarry asrow_data. - explain
- EXPLAIN renderer for query plans.
- expression
- Scalar expression evaluator (ROADMAP v0.5.0 item A).
- information_
schema information_schemavirtual tables.- key_
encoder - Lexicographic key encoding for B+tree lookups.
- rbac_
filter - RBAC query filtering and rewriting.
- window
- AUDIT-2026-04 S3.2 — SQL window functions.
Structs§
- Column
Def - Definition of a table column.
- Column
Name - SQL column name.
- Index
Def - Definition of a secondary index on a table.
- OnConflict
Clause - Parsed
ON CONFLICT (cols) DO ...clause attached to an INSERT. - Parsed
Alter Table - Parsed ALTER TABLE statement.
- Parsed
Attach Masking Policy - Parsed
ALTER TABLE <t> ALTER COLUMN <c> SET MASKING POLICY <policy>statement. - Parsed
Column - Parsed column definition.
- Parsed
Create Index - Parsed CREATE INDEX statement.
- Parsed
Create Mask - Parsed
CREATE MASK <name> ON <table>.<column> USING <strategy>statement. - Parsed
Create Masking Policy - Parsed
CREATE MASKING POLICY <name> STRATEGY <kind> [<arg>] EXEMPT ROLES (<r>, ...)statement. - Parsed
Create Table - Parsed CREATE TABLE statement.
- Parsed
Create User - Parsed CREATE USER statement.
- Parsed
Cte - A Common Table Expression (CTE) parsed from a WITH clause.
- Parsed
Delete - Parsed DELETE statement.
- Parsed
Detach Masking Policy - Parsed
ALTER TABLE <t> ALTER COLUMN <c> DROP MASKING POLICYstatement. - Parsed
Grant - Parsed GRANT statement.
- Parsed
Insert - Parsed INSERT statement.
- Parsed
Select - Parsed SELECT statement.
- Parsed
SetClassification - Parsed
ALTER TABLE <t> MODIFY COLUMN <c> SET CLASSIFICATION '<class>'. - Parsed
Union - Parsed
UNION/INTERSECT/EXCEPTstatement (with or withoutALL). - Parsed
Update - Parsed UPDATE statement.
- Prepared
Query - A prepared (planned) query ready for execution.
- Query
Engine - Query engine for executing SQL against a projection store.
- Query
Result - Result of executing a query.
- Schema
- Schema registry mapping SQL names to store types.
- Schema
Builder - Builder for constructing schemas fluently.
- Table
Def - Definition of a table in the schema.
- Table
Name - SQL table name.
Enums§
- Alter
Table Operation - ALTER TABLE operation.
- Data
Type - SQL data types supported by the query engine.
- Having
Condition - A condition in the HAVING clause.
- Having
Op - Comparison operators for HAVING conditions.
- OnConflict
Action - The action to take when
ON CONFLICT (target)fires. - Parsed
Masking Strategy - Parser-level mirror of the kernel’s
MaskingStrategyKind. Kept independent ofkimberlite-kernelso the query crate does not depend on the kernel; translation happens in the planner. - Parsed
Statement - Top-level parsed SQL statement.
- Predicate
- A comparison predicate from the WHERE clause.
- Predicate
Value - A value in a predicate (literal or parameter reference).
- Query
Error - Errors that can occur during query parsing and execution.
- Scalar
CmpOp - Comparison operator for a
Predicate::ScalarCmp. - Time
Travel - Time-travel coordinate extracted from a SQL string.
- Timestamp
Resolution - Outcome returned by a timestamp→offset resolver.
- Upsert
Expr - Expression permitted on the RHS of
SET col = <expr>insideON CONFLICT ... DO UPDATE. - Value
- A typed SQL value.
Functions§
- execute
- Executes a query plan against the current store state.
- expr_
to_ scalar_ expr - Translate a sqlparser expression into a
ScalarExpr. - extract_
at_ offset - Extracts
AT OFFSET <n>from a SQL string. - extract_
time_ travel - Extracts a
TimeTravelcoordinate from a SQL string, covering bothAT OFFSET <n>and the SQL:2011 temporal formsFOR SYSTEM_TIME AS OF '<iso8601>'andAS OF '<iso8601>'. - parse_
statement - Parses a SQL statement string into a
ParsedStatement. - plan_
query - Plans a parsed SELECT statement.
- try_
parse_ custom_ statement - Attempts to parse custom SQL extensions that
sqlparserdoes not support.