Skip to main content

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 declaration_error;
39mod declared;
40mod fold;
41mod fold_parse;
42mod lex;
43mod parse;
44mod parse_dump;
45mod parse_view;
46mod plan;
47mod render;
48mod run;
49mod schema;
50mod typemap;
51mod viewplan;
52mod viewplan_norm;
53mod viewplan_view;
54
55/// A compile error, anchored to the source: `line N, col C: message`.
56///
57/// Every refusal is *named* and teaches the kevy-shaped alternative —
58/// e.g. `JOIN is not compilable — kevy refuses query-time joins
59/// (Law 3); model the lookup with an indexed FK column …`.
60///
61/// ```
62/// let e = kevy_sql::compile("CREATE TABLE t (id bigint PRIMARY KEY, x money);").unwrap_err();
63/// assert_eq!((e.line, e.col), (1, 40));
64/// assert!(e.to_string().starts_with("line 1, col 40: "));
65/// ```
66#[derive(Debug, Clone, PartialEq, Eq, Hash)]
67#[non_exhaustive]
68pub struct SqlError {
69    /// 1-based source line.
70    ///
71    /// ```
72    /// let e = kevy_sql::compile("CREATE TABLE t (id bigint PRIMARY KEY, x money);").unwrap_err();
73    /// assert_eq!(e.line, 1);
74    /// ```
75    pub line: u32,
76    /// 1-based source column; here it points at the unmappable `money`.
77    ///
78    /// ```
79    /// let e = kevy_sql::compile("CREATE TABLE t (id bigint PRIMARY KEY, x money);").unwrap_err();
80    /// assert_eq!(e.col, 40);
81    /// ```
82    pub col: u32,
83    /// The named refusal / error text.
84    ///
85    /// ```
86    /// let e = kevy_sql::compile("CREATE TABLE t (id bigint PRIMARY KEY, x money);").unwrap_err();
87    /// assert!(e.message.contains("money"));
88    /// ```
89    pub message: String,
90}
91
92impl SqlError {
93    pub(crate) fn at(line: u32, col: u32, message: impl Into<String>) -> SqlError {
94        SqlError { line, col, message: message.into() }
95    }
96}
97
98impl std::fmt::Display for SqlError {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        write!(f, "line {}, col {}: {}", self.line, self.col, self.message)
101    }
102}
103
104impl std::error::Error for SqlError {}
105
106/// One `$N` parameter slot of a [`QueryCard`], with the column it binds
107/// and that column's declared type.
108///
109/// ```
110/// let c = kevy_sql::compile(
111///     "CREATE TABLE orders (id bigint PRIMARY KEY, user_id bigint);
112///      CREATE INDEX ON orders (user_id);
113///      CREATE VIEW by_user AS SELECT * FROM orders WHERE user_id = $1;",
114/// )?;
115/// let p = &c.query_cards[0].params[0];
116/// assert_eq!((p.n, p.column.as_str(), p.ty), (1, "user_id", kevy_sql::ValType::I64));
117/// # Ok::<(), kevy_sql::SqlError>(())
118/// ```
119#[derive(Debug, Clone, PartialEq, Eq, Hash)]
120#[non_exhaustive]
121pub struct CardParam {
122    /// The 1-based parameter number (`$1` → 1).
123    ///
124    /// ```
125    /// let c = kevy_sql::compile(
126    ///     "CREATE TABLE orders (id bigint PRIMARY KEY, user_id bigint);
127    ///      CREATE INDEX ON orders (user_id);
128    ///      CREATE VIEW by_user AS SELECT * FROM orders WHERE user_id = $1;",
129    /// )?;
130    /// assert_eq!(c.query_cards[0].params[0].n, 1);
131    /// # Ok::<(), kevy_sql::SqlError>(())
132    /// ```
133    pub n: u32,
134    /// The declared column the slot binds.
135    ///
136    /// ```
137    /// let c = kevy_sql::compile(
138    ///     "CREATE TABLE orders (id bigint PRIMARY KEY, user_id bigint);
139    ///      CREATE INDEX ON orders (user_id);
140    ///      CREATE VIEW by_user AS SELECT * FROM orders WHERE user_id = $1;",
141    /// )?;
142    /// assert_eq!(c.query_cards[0].params[0].column, "user_id");
143    /// # Ok::<(), kevy_sql::SqlError>(())
144    /// ```
145    pub column: String,
146    /// The column's declared kevy type (`i64`, `f64` or `str`: the SQL
147    /// type mapping never yields another).
148    ///
149    /// ```
150    /// let c = kevy_sql::compile(
151    ///     "CREATE TABLE orders (id bigint PRIMARY KEY, user_id bigint);
152    ///      CREATE INDEX ON orders (user_id);
153    ///      CREATE VIEW by_user AS SELECT * FROM orders WHERE user_id = $1;",
154    /// )?;
155    /// assert_eq!(c.query_cards[0].params[0].ty, kevy_sql::ValType::I64);
156    /// # Ok::<(), kevy_sql::SqlError>(())
157    /// ```
158    pub ty: ValType,
159}
160
161/// A compiled runtime template: the exact `IDX.QUERY …` argv with `$N`
162/// slots left in place. The application substitutes real values for the
163/// slots and sends the argv as-is — there is no runtime SQL.
164///
165/// ```
166/// let c = kevy_sql::compile(
167///     "CREATE TABLE orders (id bigint PRIMARY KEY, user_id bigint);
168///      CREATE INDEX ON orders (user_id);
169///      CREATE VIEW by_user AS SELECT * FROM orders WHERE user_id = $1;",
170/// )?;
171/// let card = &c.query_cards[0];
172/// // bind $1 = 42, then send the argv as-is
173/// let argv: Vec<String> =
174///     card.argv.iter().map(|a| if a == "$1" { "42".into() } else { a.clone() }).collect();
175/// assert_eq!(argv[..4], ["IDX.QUERY", "orders.user_id", "EQ", "42"]);
176/// # Ok::<(), kevy_sql::SqlError>(())
177/// ```
178#[derive(Debug, Clone, PartialEq, Eq, Hash)]
179#[non_exhaustive]
180pub struct QueryCard {
181    /// The view name the card compiles.
182    ///
183    /// ```
184    /// let c = kevy_sql::compile(
185    ///     "CREATE TABLE orders (id bigint PRIMARY KEY, user_id bigint);
186    ///      CREATE INDEX ON orders (user_id);
187    ///      CREATE VIEW by_user AS SELECT * FROM orders WHERE user_id = $1;",
188    /// )?;
189    /// assert_eq!(c.query_cards[0].name, "by_user");
190    /// # Ok::<(), kevy_sql::SqlError>(())
191    /// ```
192    pub name: String,
193    /// The full argv template (`["IDX.QUERY", "orders.user_id", "EQ",
194    /// "$1", …]`).
195    ///
196    /// ```
197    /// let c = kevy_sql::compile(
198    ///     "CREATE TABLE orders (id bigint PRIMARY KEY, user_id bigint);
199    ///      CREATE INDEX ON orders (user_id);
200    ///      CREATE VIEW by_user AS SELECT * FROM orders WHERE user_id = $1;",
201    /// )?;
202    /// assert_eq!(c.query_cards[0].argv[..4], ["IDX.QUERY", "orders.user_id", "EQ", "$1"]);
203    /// # Ok::<(), kevy_sql::SqlError>(())
204    /// ```
205    pub argv: Vec<String>,
206    /// The `$N` slots in ascending order.
207    ///
208    /// ```
209    /// let c = kevy_sql::compile(
210    ///     "CREATE TABLE orders (id bigint PRIMARY KEY, user_id bigint);
211    ///      CREATE INDEX ON orders (user_id);
212    ///      CREATE VIEW by_user AS SELECT * FROM orders WHERE user_id = $1;",
213    /// )?;
214    /// let slots: Vec<u32> = c.query_cards[0].params.iter().map(|p| p.n).collect();
215    /// assert_eq!(slots, [1]);
216    /// # Ok::<(), kevy_sql::SqlError>(())
217    /// ```
218    pub params: Vec<CardParam>,
219}
220
221/// The result of [`compile`]: engine commands, query cards, and notes.
222///
223/// ```
224/// let c = kevy_sql::compile(
225///     "CREATE TABLE orders (id bigint PRIMARY KEY, user_id bigint);
226///      CREATE INDEX ON orders (user_id);
227///      CREATE VIEW mine AS SELECT * FROM orders WHERE user_id = 7;
228///      CREATE VIEW by_user AS SELECT * FROM orders WHERE user_id = $1;",
229/// )?;
230/// assert_eq!(c.commands.len(), 2); // TABLE.DECLARE, then VIEW.CREATE
231/// assert_eq!(c.query_cards.len(), 1);
232/// # Ok::<(), kevy_sql::SqlError>(())
233/// ```
234#[derive(Debug, Clone, PartialEq, Eq, Hash)]
235#[non_exhaustive]
236pub struct Compilation {
237    /// Declaration commands in apply order: one `TABLE.DECLARE` per
238    /// table (declaration order), then the `VIEW.CREATE`s. Each is an
239    /// argv vector, ready for a RESP client.
240    ///
241    /// ```
242    /// let c = kevy_sql::compile(
243    ///     "CREATE TABLE orders (id bigint PRIMARY KEY, user_id bigint);
244    ///      CREATE INDEX ON orders (user_id);
245    ///      CREATE VIEW mine AS SELECT * FROM orders WHERE user_id = 7;
246    ///      CREATE VIEW by_user AS SELECT * FROM orders WHERE user_id = $1;",
247    /// )?;
248    /// assert_eq!(c.commands[0][..2], ["TABLE.DECLARE", "orders"]);
249    /// assert_eq!(c.commands[1][..2], ["VIEW.CREATE", "mine"]);
250    /// # Ok::<(), kevy_sql::SqlError>(())
251    /// ```
252    pub commands: Vec<Vec<String>>,
253    /// Runtime templates for parameterized / clause-bearing views,
254    /// declaration order.
255    ///
256    /// ```
257    /// let c = kevy_sql::compile(
258    ///     "CREATE TABLE orders (id bigint PRIMARY KEY, user_id bigint);
259    ///      CREATE INDEX ON orders (user_id);
260    ///      CREATE VIEW mine AS SELECT * FROM orders WHERE user_id = 7;
261    ///      CREATE VIEW by_user AS SELECT * FROM orders WHERE user_id = $1;",
262    /// )?;
263    /// assert_eq!(c.query_cards[0].name, "by_user");
264    /// # Ok::<(), kevy_sql::SqlError>(())
265    /// ```
266    pub query_cards: Vec<QueryCard>,
267    /// Honest-mapping notes (coarse type mappings, naming, read
268    /// templates) — informational, never errors.
269    ///
270    /// ```
271    /// let c = kevy_sql::compile("CREATE TABLE ev (id bigint PRIMARY KEY, at timestamp);")?;
272    /// assert!(c.notes.iter().any(|n| n.contains("ev.at: timestamp → str")));
273    /// # Ok::<(), kevy_sql::SqlError>(())
274    /// ```
275    pub notes: Vec<String>,
276}
277
278impl Compilation {
279    /// Render the compilation as a readable text artifact: commands as
280    /// pasteable lines, cards as documented comment blocks with a
281    /// machine-readable `#@card` / `#@param` / `#@argv` section (argv
282    /// tab-separated), then the notes. Deterministic.
283    ///
284    /// ```
285    /// let c = kevy_sql::compile(
286    ///     "CREATE TABLE orders (id bigint PRIMARY KEY, user_id bigint);
287    ///      CREATE INDEX ON orders (user_id);
288    ///      CREATE VIEW by_user AS SELECT * FROM orders WHERE user_id = $1;",
289    /// )?;
290    /// let script = c.render_script();
291    /// assert!(script.contains("#@card by_user"));
292    /// assert!(script.contains("#@param 1 user_id i64"));
293    /// # Ok::<(), kevy_sql::SqlError>(())
294    /// ```
295    pub fn render_script(&self) -> String {
296        render::render(self)
297    }
298}
299
300pub use declaration_error::DeclarationError;
301pub use fold::{Folded, fold_select};
302pub use kevy_index::ValType;
303pub use kevy_scalar::Scalar;
304pub use plan::{Plan, PlanEntry, Served, plan};
305pub use run::{select_card, table_ddl};
306
307/// Compile a whole SQL schema file into a [`Compilation`].
308///
309/// Whole-file semantics: statements accumulate per table (a table's
310/// `CREATE INDEX`es fold into its single `TABLE.DECLARE`), then each
311/// `CREATE VIEW` is checked against the table's *declared* access
312/// paths. The compiler never plans — a view whose WHERE has no
313/// declared path errors naming the exact `CREATE INDEX` to add.
314///
315/// ```
316/// let c = kevy_sql::compile(
317///     "CREATE TABLE orders (id bigint PRIMARY KEY, status text);
318///      CREATE INDEX ON orders (status);
319///      CREATE VIEW paid AS SELECT * FROM orders WHERE status = 'paid';",
320/// )?;
321/// assert_eq!(c.commands[1][..2], ["VIEW.CREATE", "paid"]);
322///
323/// // without the index the view has no access path, and the error says what to add
324/// let e = kevy_sql::compile(
325///     "CREATE TABLE orders (id bigint PRIMARY KEY, status text);
326///      CREATE VIEW paid AS SELECT * FROM orders WHERE status = 'paid';",
327/// )
328/// .unwrap_err();
329/// assert!(e.message.contains("add: CREATE INDEX ON orders (status)"));
330/// # Ok::<(), kevy_sql::SqlError>(())
331/// ```
332pub fn compile(sql: &str) -> Result<Compilation, SqlError> {
333    let toks = lex::lex(sql)?;
334    let stmts = parse::parse_script(&toks)?;
335    let (tables, views, mut notes) = schema::build(&stmts)?;
336    let mut commands: Vec<Vec<String>> = tables.iter().map(schema::declare_argv).collect();
337    let mut query_cards = Vec::new();
338    for v in &views {
339        let Some(t) = tables.iter().find(|t| t.name == v.table) else {
340            return Err(SqlError::at(
341                v.line,
342                v.col,
343                format!(
344                    "view '{}': FROM unknown table '{}' — CREATE TABLE it first (this compiler is whole-file: declare, then view)",
345                    v.name, v.table
346                ),
347            ));
348        };
349        match viewplan::plan_view(v, t, &mut notes)? {
350            viewplan::Planned::View(argv) => commands.push(argv),
351            viewplan::Planned::Card(card) => query_cards.push(card),
352        }
353    }
354    Ok(Compilation { commands, query_cards, notes })
355}
356
357const _: () = {
358    const fn send_sync<T: Send + Sync>() {}
359    send_sync::<SqlError>();
360    send_sync::<DeclarationError>();
361    send_sync::<CardParam>();
362    send_sync::<QueryCard>();
363    send_sync::<Compilation>();
364    send_sync::<Folded>();
365    send_sync::<Plan>();
366    send_sync::<PlanEntry>();
367    send_sync::<Served>();
368};