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 lex;
39mod parse;
40mod parse_view;
41mod render;
42mod schema;
43mod typemap;
44mod viewplan;
45mod viewplan_norm;
46mod viewplan_view;
47
48/// A compile error, anchored to the source: `line N, col C: message`.
49///
50/// Every refusal is *named* and teaches the kevy-shaped alternative —
51/// e.g. `JOIN is not compilable — kevy refuses query-time joins
52/// (Law 3); model the lookup with an indexed FK column …`.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct SqlError {
55 /// 1-based source line.
56 pub line: u32,
57 /// 1-based source column.
58 pub col: u32,
59 /// The named refusal / error text.
60 pub message: String,
61}
62
63impl SqlError {
64 pub(crate) fn at(line: u32, col: u32, message: impl Into<String>) -> SqlError {
65 SqlError { line, col, message: message.into() }
66 }
67}
68
69impl std::fmt::Display for SqlError {
70 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71 write!(f, "line {}, col {}: {}", self.line, self.col, self.message)
72 }
73}
74
75impl std::error::Error for SqlError {}
76
77/// A kevy column type — the deliberately coarse target of the SQL type
78/// mapping (kevy columns are `i64 | f64 | str`; timestamps and the like
79/// are app-encoded strings).
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub enum KevyType {
82 /// 64-bit signed integer (`int`/`integer`/`bigint`/`serial`/`bigserial`).
83 I64,
84 /// 64-bit float (`real`/`float`/`double precision`/`numeric`/`decimal`).
85 F64,
86 /// Byte string (`text`/`varchar`/`char`/`uuid`/`timestamp`/`timestamptz`/
87 /// `date`/`bool`/`boolean`/`json`/`jsonb`).
88 Str,
89}
90
91impl KevyType {
92 /// The wire tag (`i64` / `f64` / `str`) as it appears in
93 /// `TABLE.DECLARE … COLUMN <name> <tag>`.
94 pub fn tag(self) -> &'static str {
95 match self {
96 KevyType::I64 => "i64",
97 KevyType::F64 => "f64",
98 KevyType::Str => "str",
99 }
100 }
101}
102
103/// One `$N` parameter slot of a [`QueryCard`], with the column it binds
104/// and that column's declared type.
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub struct CardParam {
107 /// The 1-based parameter number (`$1` → 1).
108 pub n: u32,
109 /// The declared column the slot binds.
110 pub column: String,
111 /// The column's declared kevy type.
112 pub ty: KevyType,
113}
114
115/// A compiled runtime template: the exact `IDX.QUERY …` argv with `$N`
116/// slots left in place. The application substitutes real values for the
117/// slots and sends the argv as-is — there is no runtime SQL.
118#[derive(Debug, Clone, PartialEq, Eq)]
119pub struct QueryCard {
120 /// The view name the card compiles.
121 pub name: String,
122 /// The full argv template (`["IDX.QUERY", "orders.user_id", "EQ",
123 /// "$1", …]`).
124 pub argv: Vec<String>,
125 /// The `$N` slots in ascending order.
126 pub params: Vec<CardParam>,
127}
128
129/// The result of [`compile`]: engine commands, query cards, and notes.
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct Compilation {
132 /// Declaration commands in apply order: one `TABLE.DECLARE` per
133 /// table (declaration order), then the `VIEW.CREATE`s. Each is an
134 /// argv vector, ready for a RESP client.
135 pub commands: Vec<Vec<String>>,
136 /// Runtime templates for parameterized / clause-bearing views,
137 /// declaration order.
138 pub query_cards: Vec<QueryCard>,
139 /// Honest-mapping notes (coarse type mappings, naming, read
140 /// templates) — informational, never errors.
141 pub notes: Vec<String>,
142}
143
144impl Compilation {
145 /// Render the compilation as a readable text artifact: commands as
146 /// pasteable lines, cards as documented comment blocks with a
147 /// machine-readable `#@card` / `#@param` / `#@argv` section (argv
148 /// tab-separated), then the notes. Deterministic.
149 pub fn render_script(&self) -> String {
150 render::render(self)
151 }
152}
153
154/// Compile a whole SQL schema file into a [`Compilation`].
155///
156/// Whole-file semantics: statements accumulate per table (a table's
157/// `CREATE INDEX`es fold into its single `TABLE.DECLARE`), then each
158/// `CREATE VIEW` is checked against the table's *declared* access
159/// paths. The compiler never plans — a view whose WHERE has no
160/// declared path errors naming the exact `CREATE INDEX` to add.
161pub fn compile(sql: &str) -> Result<Compilation, SqlError> {
162 let toks = lex::lex(sql)?;
163 let stmts = parse::parse_script(&toks)?;
164 let (tables, views, mut notes) = schema::build(&stmts)?;
165 let mut commands: Vec<Vec<String>> = tables.iter().map(schema::declare_argv).collect();
166 let mut query_cards = Vec::new();
167 for v in &views {
168 let Some(t) = tables.iter().find(|t| t.name == v.table) else {
169 return Err(SqlError::at(
170 v.line,
171 v.col,
172 format!(
173 "view '{}': FROM unknown table '{}' — CREATE TABLE it first (this compiler is whole-file: declare, then view)",
174 v.name, v.table
175 ),
176 ));
177 };
178 match viewplan::plan_view(v, t, &mut notes)? {
179 viewplan::Planned::View(argv) => commands.push(argv),
180 viewplan::Planned::Card(card) => query_cards.push(card),
181 }
182 }
183 Ok(Compilation { commands, query_cards, notes })
184}