kevy_sql/lib.rs
1//! kevy-sql — the OUT-OF-ENGINE, declaration-time SQL compiler.
2//!
3//! This tool compiles a schema ONCE, at declaration time, into explicit
4//! kevy engine commands (`TABLE.DECLARE`, `VIEW.CREATE`) plus *query
5//! cards* — ready-made `IDX.QUERY` templates an application binds
6//! parameters into at runtime. It is a build step, like a schema
7//! migration tool. **Nothing here ever runs per-query inside a serving
8//! process**: ad-hoc runtime SQL stays refused by the engine itself
9//! (unknown command), and this compiler refuses — by name, with
10//! line/column — every SQL construct that would need query-time
11//! evaluation (JOIN, subqueries, GROUP BY, expressions…). That is
12//! kevy's Law 3: meaning and planning never enter the engine.
13//!
14//! The honest pitch: **your schema's access paths, compiled — not a
15//! drop-in PG.** `CREATE TABLE` becomes a typed, verifiable
16//! `TABLE.DECLARE`; `CREATE [UNIQUE] INDEX` becomes declared Range /
17//! Unique / composite ORDERPATH access paths; single-table
18//! `CREATE VIEW … AS SELECT` becomes either an engine view (constant
19//! predicates) or a query card (parameterized / clause-bearing). The
20//! compiler never plans: a WHERE clause either matches a declared
21//! access path (leading-prefix rule) or the compile errors naming the
22//! exact declaration to add.
23//!
24//! ```
25//! let sql = "
26//! CREATE TABLE users (id bigint PRIMARY KEY, email text);
27//! CREATE UNIQUE INDEX ON users (email);
28//! ";
29//! let c = kevy_sql::compile(sql).unwrap();
30//! assert_eq!(c.commands[0][0], "TABLE.DECLARE");
31//! println!("{}", c.render_script());
32//! ```
33
34#![forbid(unsafe_code)]
35#![warn(missing_docs)]
36
37mod ast;
38mod fold;
39mod fold_parse;
40mod lex;
41mod parse;
42mod parse_dump;
43mod parse_view;
44mod plan;
45mod render;
46mod schema;
47mod typemap;
48mod viewplan;
49mod viewplan_norm;
50mod viewplan_view;
51
52/// A compile error, anchored to the source: `line N, col C: message`.
53///
54/// Every refusal is *named* and teaches the kevy-shaped alternative —
55/// e.g. `JOIN is not compilable — kevy refuses query-time joins
56/// (Law 3); model the lookup with an indexed FK column …`.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct SqlError {
59 /// 1-based source line.
60 pub line: u32,
61 /// 1-based source column.
62 pub col: u32,
63 /// The named refusal / error text.
64 pub message: String,
65}
66
67impl SqlError {
68 pub(crate) fn at(line: u32, col: u32, message: impl Into<String>) -> SqlError {
69 SqlError { line, col, message: message.into() }
70 }
71}
72
73impl std::fmt::Display for SqlError {
74 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75 write!(f, "line {}, col {}: {}", self.line, self.col, self.message)
76 }
77}
78
79impl std::error::Error for SqlError {}
80
81/// A kevy column type — the deliberately coarse target of the SQL type
82/// mapping (kevy columns are `i64 | f64 | str`; timestamps and the like
83/// are app-encoded strings).
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum KevyType {
86 /// 64-bit signed integer (`int`/`integer`/`bigint`/`serial`/`bigserial`).
87 I64,
88 /// 64-bit float (`real`/`float`/`double precision`/`numeric`/`decimal`).
89 F64,
90 /// Byte string (`text`/`varchar`/`char`/`uuid`/`timestamp`/`timestamptz`/
91 /// `date`/`bool`/`boolean`/`json`/`jsonb`).
92 Str,
93}
94
95impl KevyType {
96 /// The wire tag (`i64` / `f64` / `str`) as it appears in
97 /// `TABLE.DECLARE … COLUMN <name> <tag>`.
98 pub fn tag(self) -> &'static str {
99 match self {
100 KevyType::I64 => "i64",
101 KevyType::F64 => "f64",
102 KevyType::Str => "str",
103 }
104 }
105}
106
107/// One `$N` parameter slot of a [`QueryCard`], with the column it binds
108/// and that column's declared type.
109#[derive(Debug, Clone, PartialEq, Eq)]
110pub struct CardParam {
111 /// The 1-based parameter number (`$1` → 1).
112 pub n: u32,
113 /// The declared column the slot binds.
114 pub column: String,
115 /// The column's declared kevy type.
116 pub ty: KevyType,
117}
118
119/// A compiled runtime template: the exact `IDX.QUERY …` argv with `$N`
120/// slots left in place. The application substitutes real values for the
121/// slots and sends the argv as-is — there is no runtime SQL.
122#[derive(Debug, Clone, PartialEq, Eq)]
123pub struct QueryCard {
124 /// The view name the card compiles.
125 pub name: String,
126 /// The full argv template (`["IDX.QUERY", "orders.user_id", "EQ",
127 /// "$1", …]`).
128 pub argv: Vec<String>,
129 /// The `$N` slots in ascending order.
130 pub params: Vec<CardParam>,
131}
132
133/// The result of [`compile`]: engine commands, query cards, and notes.
134#[derive(Debug, Clone, PartialEq, Eq)]
135pub struct Compilation {
136 /// Declaration commands in apply order: one `TABLE.DECLARE` per
137 /// table (declaration order), then the `VIEW.CREATE`s. Each is an
138 /// argv vector, ready for a RESP client.
139 pub commands: Vec<Vec<String>>,
140 /// Runtime templates for parameterized / clause-bearing views,
141 /// declaration order.
142 pub query_cards: Vec<QueryCard>,
143 /// Honest-mapping notes (coarse type mappings, naming, read
144 /// templates) — informational, never errors.
145 pub notes: Vec<String>,
146}
147
148impl Compilation {
149 /// Render the compilation as a readable text artifact: commands as
150 /// pasteable lines, cards as documented comment blocks with a
151 /// machine-readable `#@card` / `#@param` / `#@argv` section (argv
152 /// tab-separated), then the notes. Deterministic.
153 pub fn render_script(&self) -> String {
154 render::render(self)
155 }
156}
157
158pub use fold::{Folded, fold_select};
159pub use kevy_scalar::Scalar;
160pub use plan::{Plan, PlanEntry, Served, plan};
161
162/// Compile a whole SQL schema file into a [`Compilation`].
163///
164/// Whole-file semantics: statements accumulate per table (a table's
165/// `CREATE INDEX`es fold into its single `TABLE.DECLARE`), then each
166/// `CREATE VIEW` is checked against the table's *declared* access
167/// paths. The compiler never plans — a view whose WHERE has no
168/// declared path errors naming the exact `CREATE INDEX` to add.
169pub fn compile(sql: &str) -> Result<Compilation, SqlError> {
170 let toks = lex::lex(sql)?;
171 let stmts = parse::parse_script(&toks)?;
172 let (tables, views, mut notes) = schema::build(&stmts)?;
173 let mut commands: Vec<Vec<String>> = tables.iter().map(schema::declare_argv).collect();
174 let mut query_cards = Vec::new();
175 for v in &views {
176 let Some(t) = tables.iter().find(|t| t.name == v.table) else {
177 return Err(SqlError::at(
178 v.line,
179 v.col,
180 format!(
181 "view '{}': FROM unknown table '{}' — CREATE TABLE it first (this compiler is whole-file: declare, then view)",
182 v.name, v.table
183 ),
184 ));
185 };
186 match viewplan::plan_view(v, t, &mut notes)? {
187 viewplan::Planned::View(argv) => commands.push(argv),
188 viewplan::Planned::Card(card) => query_cards.push(card),
189 }
190 }
191 Ok(Compilation { commands, query_cards, notes })
192}