Skip to main content

kevy_sql/
run.rs

1//! The two faces that start from a live catalog instead of a schema
2//! file: [`select_card`] (`kevy-cli sql run`) and [`table_ddl`]
3//! (`kevy-cli show-create --as sql`). Both take `TABLE.DECLARE` argv —
4//! what `TABLE.DESCRIBE` returns as `declaration` — so the compiler
5//! plans against exactly what the server holds.
6
7use crate::ast::CreateView;
8use crate::declared::{self, Declared};
9use crate::lex::{Tok, lex};
10use crate::parse::P;
11use crate::schema::Table;
12use crate::{DeclarationError, QueryCard, SqlError, ValType, parse_view, viewplan};
13
14/// One `SELECT … FROM t WHERE …` as the `IDX.QUERY` argv that answers
15/// it over `t`'s declared paths. Values are literals; a `$N` slot is a
16/// card parameter and is refused here (that is `sql compile`'s shape).
17/// A query no declared path serves is refused with the same text
18/// `sql plan` gives it. Never an engine view: a view is a declaration,
19/// and this answers a query now.
20///
21/// ```
22/// let orders: Vec<String> = "TABLE.DECLARE orders PREFIX orders: PK id COLUMN id i64 \
23///     COLUMN user_id i64 COLUMN total f64 INDEX user_id range VALUES total"
24///     .split_whitespace()
25///     .map(String::from)
26///     .collect();
27/// let card = kevy_sql::select_card(&[orders.clone()], "SELECT id FROM orders WHERE user_id = 7").unwrap();
28/// assert_eq!(card.argv.join(" "), "IDX.QUERY orders.user_id EQ 7 FIELDS id");
29///
30/// let refused = kevy_sql::select_card(&[orders], "SELECT id FROM orders WHERE total >= 1").unwrap_err();
31/// assert!(refused.message.contains("total"), "{refused}");
32/// ```
33pub fn select_card(declarations: &[Vec<String>], select: &str) -> Result<QueryCard, SqlError> {
34    let v = parse_one_select(select)?;
35    let tables = declarations
36        .iter()
37        .map(|argv| declared::read(argv).map_err(|e| SqlError::at(v.line, v.col, e.to_string())))
38        .collect::<Result<Vec<Declared>, SqlError>>()?;
39    let Some(d) = tables.iter().find(|d| d.table.name == v.table) else {
40        return Err(SqlError::at(
41            v.line,
42            v.col,
43            format!(
44                "FROM unknown table '{}' \u{2014} TABLE.LIST enumerates the declared tables",
45                v.table
46            ),
47        ));
48    };
49    let card = viewplan::card_for(&v, &d.table)?;
50    if let Some(p) = card.params.first() {
51        return Err(SqlError::at(
52            v.line,
53            v.col,
54            format!(
55                "${} is a query-card parameter \u{2014} sql run takes literal values; `sql compile` makes cards",
56                p.n
57            ),
58        ));
59    }
60    Ok(card)
61}
62
63fn parse_one_select(select: &str) -> Result<CreateView, SqlError> {
64    let toks = lex(select)?;
65    let mut p = P::new(&toks);
66    let t = p.peek();
67    let (line, col) = (t.line, t.col);
68    p.expect_kw("select", "\u{2014} sql run takes one SELECT")?;
69    let v = parse_view::parse_select_body(&mut p, "select".into(), line, col)?;
70    while p.eat_sym(';') {}
71    if !matches!(p.peek().tok, Tok::Eof) {
72        return Err(
73            p.err_here("expected the end of the SELECT \u{2014} sql run takes one statement")
74        );
75    }
76    Ok(v)
77}
78
79/// A `TABLE.DECLARE` argv as the SQL `sql compile` turns back into the
80/// same declaration: `CREATE TABLE`, then one `CREATE [UNIQUE] INDEX` per
81/// index and order path, in declaration order. What SQL has no words for
82/// — a key prefix other than `<table>:`, `WINDOW`, `AUTODECLARE`, a
83/// one-column order path — is written as a `--` comment naming the
84/// clause, so a reader sees what the SQL form does not carry.
85///
86/// ```
87/// let decl: Vec<String> = "TABLE.DECLARE users PREFIX users: PK id COLUMN id i64 \
88///     COLUMN email str INDEX email unique"
89///     .split_whitespace()
90///     .map(String::from)
91///     .collect();
92/// let ddl = kevy_sql::table_ddl(&decl).unwrap();
93/// assert_eq!(
94///     ddl,
95///     "CREATE TABLE users (\n    id bigint PRIMARY KEY,\n    email text\n);\n\
96///      CREATE UNIQUE INDEX ON users (email);\n"
97/// );
98/// assert_eq!(kevy_sql::compile(&ddl).unwrap().commands, vec![decl]);
99/// ```
100pub fn table_ddl(declaration: &[String]) -> Result<String, DeclarationError> {
101    let d = declared::read(declaration)?;
102    let t = &d.table;
103    let mut out = String::new();
104    let mut lost: Vec<String> = Vec::new();
105    if d.prefix != format!("{}:", t.name) {
106        lost.push(format!("PREFIX {}", d.prefix));
107    }
108    out.push_str(&format!("CREATE TABLE {} (\n", ident(&t.name)?));
109    let mut lines = Vec::new();
110    for (c, ty) in &t.columns {
111        let pk = if *c == t.pk { " PRIMARY KEY" } else { "" };
112        lines.push(format!("    {} {}{pk}", ident(c)?, sql_type(*ty)));
113    }
114    out.push_str(&lines.join(",\n"));
115    out.push_str("\n);\n");
116    indexes(t, &mut out)?;
117    orderpaths(t, &mut out, &mut lost)?;
118    lost.extend(d.beyond_sql.iter().map(|words| words.join(" ")));
119    for clause in lost {
120        out.push_str(&format!("-- not carried by SQL: {clause}\n"));
121    }
122    Ok(out)
123}
124
125fn indexes(t: &Table, out: &mut String) -> Result<(), DeclarationError> {
126    for ix in &t.indexes {
127        let unique = if ix.unique { "UNIQUE " } else { "" };
128        out.push_str(&format!(
129            "CREATE {unique}INDEX ON {} ({})",
130            ident(&t.name)?,
131            ident(&ix.column)?
132        ));
133        if !ix.values.is_empty() {
134            out.push_str(&format!(" INCLUDE ({})", idents(&ix.values)?));
135        }
136        out.push_str(";\n");
137    }
138    Ok(())
139}
140
141/// A composite index per order path. SQL reads a one-column index as a
142/// plain index, so a one-column order path is noted instead.
143fn orderpaths(t: &Table, out: &mut String, lost: &mut Vec<String>) -> Result<(), DeclarationError> {
144    for op in &t.orderpaths {
145        if let [(c, true)] = op.on.as_slice() {
146            // One descending column reads back as the same order path.
147            let stmt = format!(
148                "CREATE INDEX {} ON {} ({} DESC);\n",
149                ident(&op.name)?,
150                ident(&t.name)?,
151                ident(c)?
152            );
153            out.push_str(&stmt);
154            continue;
155        }
156        if op.on.len() < 2 {
157            let on: Vec<String> = op
158                .on
159                .iter()
160                .map(|(c, desc)| if *desc { format!("{c} DESC") } else { c.clone() })
161                .collect();
162            lost.push(format!("ORDERPATH {} ON {}", op.name, on.join(" THEN ")));
163            continue;
164        }
165        let cols = op
166            .on
167            .iter()
168            .map(|(c, desc)| Ok(format!("{}{}", ident(c)?, if *desc { " DESC" } else { "" })))
169            .collect::<Result<Vec<String>, DeclarationError>>()?
170            .join(", ");
171        out.push_str(&format!(
172            "CREATE INDEX {} ON {} ({cols});\n",
173            ident(&op.name)?,
174            ident(&t.name)?
175        ));
176    }
177    Ok(())
178}
179
180fn sql_type(ty: ValType) -> &'static str {
181    match ty {
182        ValType::I64 => "bigint",
183        ValType::F64 => "double precision",
184        ValType::Str => "text",
185        // `declared` admits only the three column types above
186        _ => unreachable!("a declared column is i64, f64 or str"),
187    }
188}
189
190/// A name as the lexer reads it back: bare when it is already a
191/// lower-case identifier, `"quoted"` otherwise. A `"` inside a name has
192/// no spelling in this dialect, so it is refused rather than mangled.
193fn ident(name: &str) -> Result<String, DeclarationError> {
194    let bare = name.bytes().next().is_some_and(|b| b.is_ascii_lowercase() || b == b'_')
195        && name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_');
196    if bare {
197        Ok(name.to_string())
198    } else if name.contains('"') {
199        Err(DeclarationError::Unspellable(name.to_string()))
200    } else {
201        Ok(format!("\"{name}\""))
202    }
203}
204
205fn idents(names: &[String]) -> Result<String, DeclarationError> {
206    Ok(names
207        .iter()
208        .map(|n| ident(n))
209        .collect::<Result<Vec<String>, DeclarationError>>()?
210        .join(", "))
211}
212
213#[cfg(test)]
214#[path = "run_tests.rs"]
215mod tests;