Skip to main content

reylo_engine_core/
api.rs

1//! The request and response vocabulary every host speaks: the loader's `src/engine.ts` and the
2//! oracle.
3//!
4//! `analyze` is a replay: the host calls it with the answers it has, the engine either returns
5//! the analysis or the list of things it still needs — statements to describe, catalog queries
6//! to run — and the host calls again with those answered. The engine is pure, so every round
7//! starts from the statement text and the answers; nothing is kept between calls.
8//!
9//! Each artifact serves one database ([`call`] for one [`Database`]): `lex` and `config` are core's
10//! and answer for any dialect, `ping` names the database the artifact reads, and an `analyze` for
11//! another database's statement is refused by name.
12
13use crate::database::Database;
14use crate::dialect::Dialect;
15use crate::lex;
16use crate::types::{self, Cardinality, DialectVersion, ResultRows, StatementDescriptor, StatementKind, Type};
17use serde::de::DeserializeOwned;
18use serde::{Deserialize, Serialize};
19use serde_json::Value;
20use std::collections::HashMap;
21
22#[derive(Debug, Deserialize)]
23#[serde(tag = "op", rename_all = "camelCase", bound(deserialize = "D: DeserializeOwned"))]
24pub enum Request<D> {
25    /// Round-trip check: answers with the engine version, its fingerprint and its database.
26    Ping,
27    /// Placeholders only; no database.
28    Lex { sql: String, dialect: Dialect },
29    /// The project file's text, `.reylo.yaml`.
30    Config { text: String },
31    /// The whole analysis, given what the host has answered so far.
32    Analyze {
33        sql: String,
34        dialect: Dialect,
35        #[serde(default)]
36        answers: Answers<D>,
37    },
38}
39
40/// What a database's `describe` need is answered with ([`Database::Describe`]).
41pub trait Describe: DeserializeOwned + Clone + std::fmt::Debug + Send + Sync + 'static {}
42impl<T: DeserializeOwned + Clone + std::fmt::Debug + Send + Sync + 'static> Describe for T {}
43
44/// What the host learned for one need, keyed by the need's id. The describe payload is the
45/// database's own: Postgres's Parse/Describe, MySQL's prepare metadata, nothing for SQLite.
46#[derive(Debug, Clone, Deserialize)]
47#[serde(untagged)]
48pub enum Answer<D> {
49    /// `{"describe": …}`. A MySQL host writes `{"mysql": …}`, which reads the same.
50    Describe {
51        #[serde(alias = "mysql")]
52        describe: D,
53    },
54    Rows { rows: Vec<Vec<Value>> },
55    Error { error: DbError },
56}
57
58/// The answers of a request, by need id.
59pub type Answers<D> = HashMap<String, Answer<D>>;
60
61/// The payload of a database that never asks for a describe: SQLite prepares inside the engine.
62/// No describe answer reads as one.
63#[derive(Debug, Clone, Deserialize)]
64pub enum NoDescribe {}
65
66#[derive(Debug, Clone, Deserialize, Serialize)]
67pub struct DbError {
68    pub message: String,
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub code: Option<String>,
71    /// The 1-based character position the server reported, in the text it was given.
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub position: Option<usize>,
74}
75
76#[derive(Debug, Clone, Serialize, PartialEq)]
77#[serde(tag = "kind", rename_all = "camelCase")]
78pub enum Need {
79    /// Prepare `sql` and report its parameter types and result columns.
80    Describe { id: String, sql: String },
81    /// Run `sql` with `params` and hand back the rows as arrays of values.
82    Query { id: String, sql: String, params: Vec<Value>, scope: Scope },
83}
84
85/// How long an answer stays true: a session answer is about the database as a whole and the
86/// host may keep it across statements; a statement one is about this statement's relations.
87#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
88#[serde(rename_all = "lowercase")]
89pub enum Scope {
90    Session,
91    Statement,
92}
93
94/// A diagnostic as Reylo's own tools read it: its place in UTF-8 bytes and Reylo's code for it
95/// ([`types::Diagnostic`] is the format's, in UTF-16 units and with the database's code).
96#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
97pub struct Diagnostic {
98    pub message: String,
99    /// Byte offset in the original text.
100    pub start: usize,
101    pub length: usize,
102    pub code: u32,
103    /// The database's own code for the error the diagnostic reports (Postgres's SQLSTATE `42703`,
104    /// MySQL's `1054`), where the database raised it.
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub server_code: Option<String>,
107}
108
109/// A statement's parameter: the format's ([`types::Param`]) and what Reylo's run time reads
110/// beside it.
111#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct Param {
113    pub name: String,
114    #[serde(rename = "type")]
115    pub ty: Type,
116    /// Whether the caller may pass null: the statement tests the parameter for null or
117    /// coalesces it, or it is the whole value written to a nullable column.
118    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
119    pub nullable: bool,
120    /// Whether the caller may leave the parameter out: a typed JSON parameter whose schema has a
121    /// `default`.
122    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
123    pub optional: bool,
124    /// The comment the database keeps on the column the parameter is written to (or, on MySQL,
125    /// compared with), for the parameter's doc comment.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub comment: Option<String>,
128    /// A typed JSON parameter's JSON Schema as its cast writes it (`:p::jsonb('…')`), which the
129    /// run time checks a value against; its type is the schema as the engine reads it.
130    #[serde(default, skip_serializing_if = "Option::is_none")]
131    pub schema: Option<Value>,
132    /// A `::type` written on MySQL or SQLite as the dialect's own cast, which turns a value it
133    /// cannot read into 0, so the run time checks the parameter's value against its type.
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub cast: Option<String>,
136    /// What separates the elements of an array parameter's text, where the element type's
137    /// `typdelim` is not a comma (`:` for PostGIS's `geometry`, `;` for `box`): the run time
138    /// writes the array's text with it.
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub delimiter: Option<String>,
141    /// A structured parameter's members as its column list writes them, in the order of its
142    /// record's fields ([`crate::structured`]), which the run time checks each value against.
143    #[serde(default, skip_serializing_if = "Vec::is_empty")]
144    pub members: Vec<Member>,
145}
146
147/// A structured parameter's member as its column list writes it.
148#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
149pub struct Member {
150    /// The type as the column list writes it (`varchar(32)`, `numeric(12,2)`), for the run time's
151    /// messages and the modifiers it checks.
152    pub written: String,
153    /// A `json('…')` member's JSON Schema as written, which the run time checks a value against.
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub schema: Option<Value>,
156}
157
158impl Param {
159    /// A parameter of `ty`, with nothing else known of it.
160    pub fn new(name: impl Into<String>, ty: Type) -> Param {
161        Param { name: name.into(), ty, nullable: false, optional: false, comment: None, schema: None, cast: None, delimiter: None, members: Vec::new() }
162    }
163
164    /// The parameter as the format writes it.
165    pub fn descriptor(&self) -> types::Param {
166        types::Param { name: self.name.clone(), ty: self.ty.clone(), nullable: self.nullable, optional: self.optional, comment: self.comment.clone() }
167    }
168}
169
170/// A result column: the format's field of a row ([`types::Field`]) and what Reylo's run time reads beside it.
171#[derive(Debug, Clone, Serialize, Deserialize)]
172pub struct Column {
173    pub name: String,
174    #[serde(rename = "type")]
175    pub ty: Type,
176    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
177    pub nullable: bool,
178    /// The comment the database keeps on the table column the result column reads as it is
179    /// (`COMMENT ON COLUMN`, MySQL's `COMMENT '…'`), for the field's doc comment; none for an
180    /// expression.
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub comment: Option<String>,
183    /// What separates the elements of an array column's text, where it is not a comma, which the
184    /// run time reads the array's text with ([`Param::delimiter`]).
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub delimiter: Option<String>,
187}
188
189impl Column {
190    /// A column of `ty`, with nothing else known of it.
191    pub fn new(name: impl Into<String>, ty: Type, nullable: bool) -> Column {
192        Column { name: name.into(), ty, nullable, comment: None, delimiter: None }
193    }
194
195    /// The column as the format writes it: a field of the result's record.
196    pub fn descriptor(&self) -> types::Field {
197        types::Field { comment: self.comment.clone(), ..types::Field::new(self.name.clone(), self.ty.clone(), self.nullable) }
198    }
199}
200
201#[derive(Debug, Clone, Serialize)]
202#[serde(rename_all = "camelCase")]
203pub struct Analysis {
204    /// The statement's kind: one of the five, `other` for any other, absent when it did not parse.
205    #[serde(skip_serializing_if = "Option::is_none")]
206    pub kind: Option<StatementKind>,
207    /// The prose written in comments before the statement ([`crate::comment::leading`]).
208    #[serde(skip_serializing_if = "Option::is_none")]
209    pub comment: Option<String>,
210    pub params: Vec<Param>,
211    pub columns: Vec<Column>,
212    /// How many rows the statement returns.
213    pub cardinality: Cardinality,
214    /// Why the proof stopped short of `one`, when it did.
215    #[serde(skip_serializing_if = "Option::is_none")]
216    pub cardinality_reason: Option<String>,
217    /// The result key: output columns, by name, that identify each row of the result, since no two
218    /// rows the statement returns agree on all of them (a NULL counting as equal to another NULL).
219    /// Only for a result that can hold more than one row: `None` where the cardinality is `one` or
220    /// `at_most_one`, which says as much, and where no key is proven, which is always sound.
221    #[serde(skip_serializing_if = "Option::is_none")]
222    pub key: Option<Vec<String>>,
223    /// Every set of output columns no two rows agree on all of, as `key` is, none inside another,
224    /// and a table's primary key first where the result holds it. Empty where none is proven.
225    #[serde(default, skip_serializing_if = "Vec::is_empty")]
226    pub unique: Vec<Vec<String>>,
227    /// The columns of the result its ORDER BY sorts on, as far as its keys are such columns.
228    #[serde(default, skip_serializing_if = "Vec::is_empty")]
229    pub order: Vec<types::SortKey>,
230    /// Whether the statement's ORDER BY orders its rows totally: no two rows of any result tie on
231    /// every sort key, so the order is the same on every run. Only for a result that can hold more
232    /// than one row, as `key` is.
233    #[serde(skip_serializing_if = "std::ops::Not::not")]
234    pub ordered: bool,
235    /// Whether the result is its one column's values, not rows that hold them: the statement's one
236    /// column is an expression it gives no name, so the only name it has is one the database makes
237    /// up ([`crate::analysis::names`]).
238    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
239    pub value: bool,
240    pub rewritten: lex::Rewritten,
241    /// How the session the statement was read on reads MySQL's strings and double quotes, by its
242    /// `sql_mode`, where another mode would read the statement otherwise: its placeholders hold
243    /// only for a session that reads it so. Absent where every mode reads it alike, and on every
244    /// other database.
245    #[serde(skip_serializing_if = "Option::is_none")]
246    pub sql_mode: Option<lex::MysqlText>,
247    pub style: lex::Style,
248    pub diagnostics: Vec<Diagnostic>,
249    /// Paths inside JSON columns the engine could not type, for a message.
250    pub unresolved: Vec<String>,
251    /// Each structured parameter in insert position, with the lists of `rewritten` the run time
252    /// writes again for a call that leaves keys out ([`crate::structured`]); on the wire only
253    /// those that have lists (MySQL's), since a Postgres or SQLite statement copies its defaults.
254    #[serde(skip_serializing_if = "crate::structured::none_rewritten", serialize_with = "crate::structured::rewritten_only")]
255    pub structured: Vec<crate::structured::Info>,
256    /// The names each error the statement may raise can carry, where it runs only its database's
257    /// own code ([`crate::errors`]).
258    #[serde(skip_serializing_if = "Option::is_none")]
259    pub errors: Option<crate::errors::Errors>,
260    /// What running the statement may do, an upper bound ([`types::Capabilities`]); absent where
261    /// nothing is said.
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub capabilities: Option<types::Capabilities>,
264    /// Whether the engine finds nothing in the statement that could write, so that a caller may run it again after
265    /// a lost connection ([`crate::database::Database::read_only`]).
266    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
267    pub read_only: bool,
268    /// Each domain a type of the statement is named by, with the name of the base type it is made
269    /// from: a client decodes a domain's values as its base type's (a Postgres domain over
270    /// pgvector's `vector` comes as the vector's text), which the format leaves to the catalog.
271    #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
272    pub domains: std::collections::BTreeMap<String, String>,
273    /// What is worth saying of the statement but fails nothing, for a hover: the type check has no
274    /// level below an error.
275    #[serde(skip_serializing_if = "Vec::is_empty")]
276    pub notes: Vec<String>,
277    /// The tables the statement reads and writes, as its database's own parse names them
278    /// ([`crate::fresh::Tables`]). On the wire only where the analysis read a function's body,
279    /// whose tables a parse of the statement as written cannot give: so a server's analysis
280    /// carries them to its client.
281    #[serde(skip_serializing_if = "reads_no_body")]
282    pub tables: Option<crate::fresh::Tables>,
283}
284
285fn reads_no_body(tables: &Option<crate::fresh::Tables>) -> bool {
286    tables.as_ref().is_none_or(|t| t.functions.is_empty())
287}
288
289impl Analysis {
290    /// The statement as the format describes it ([`StatementDescriptor`]): `sql` is the statement
291    /// as it was written, which the diagnostics' offsets index, and `dialect` the database and
292    /// version the analysis read.
293    pub fn descriptor(&self, sql: &str, dialect: DialectVersion) -> StatementDescriptor {
294        StatementDescriptor {
295            schema: types::SCHEMA.to_string(),
296            dialect,
297            sql: self.rewritten.sql.clone(),
298            kind: self.kind,
299            comment: self.comment.clone(),
300            params: self.params.iter().map(Param::descriptor).collect(),
301            result: ResultRows::new(self.cardinality, self.columns.iter().map(Column::descriptor).collect(), self.unique.clone(), self.order.clone()),
302            capabilities: self.capabilities.clone(),
303            diagnostics: self.diagnostics.iter().map(|d| {
304                let start = utf16_offset(sql, d.start);
305                types::Diagnostic { message: d.message.clone(), start, end: utf16_offset(sql, d.start + d.length).max(start), code: d.server_code.clone() }
306            }).collect(),
307        }
308    }
309}
310
311/// The UTF-16 offset of the UTF-8 byte offset `byte` of `text`, as the format counts: a byte
312/// inside a character counts from the character's start, and one past the end at the end.
313pub fn utf16_offset(text: &str, byte: usize) -> usize {
314    let mut at = byte.min(text.len());
315    while !text.is_char_boundary(at) {
316        at -= 1;
317    }
318    text[..at].encode_utf16().count()
319}
320
321#[derive(Debug, Serialize)]
322#[serde(tag = "status", rename_all = "camelCase")]
323pub enum Response {
324    Ok {
325        version: String,
326        fingerprint: String,
327        /// The database whose statements this artifact reads.
328        #[serde(skip_serializing_if = "Option::is_none")]
329        database: Option<Dialect>,
330    },
331    Lexed { lexed: lex::Lexed },
332    Config { config: crate::config::Project },
333    ConfigError { error: crate::config::ConfigError },
334    Need { needs: Vec<Need> },
335    Analysis { analysis: Analysis },
336    Error { message: String },
337}
338
339/// What a request says before its answers are read: what a host that links several databases
340/// dispatches on, and what lets [`call`] refuse another database's statement by name.
341#[derive(Debug, Deserialize)]
342struct Head {
343    #[serde(default)]
344    op: String,
345    #[serde(default)]
346    dialect: Option<Dialect>,
347}
348
349/// The dialect a request names, if it names one it can be read for.
350pub fn dialect_of(request: &str) -> Option<Dialect> {
351    serde_json::from_str::<Head>(request).ok()?.dialect
352}
353
354/// One request in, one response out, both JSON text, for the database `D`: the only entry point
355/// of a database's artifact.
356pub fn call<D: Database>(request: &str) -> String {
357    crate::stack::run(|| call_here::<D>(request))
358}
359
360fn call_here<D: Database>(request: &str) -> String {
361    let head = serde_json::from_str::<Head>(request).ok();
362    let response = match head {
363        Some(Head { op, dialect: Some(other) }) if op == "analyze" && other != D::DIALECT => {
364            Response::Error { message: format!("this engine reads {} statements, not {} ones", D::DIALECT.name(), other.name()) }
365        }
366        _ => match serde_json::from_str::<Request<D::Describe>>(request) {
367            Ok(Request::Ping) => Response::Ok { version: env!("CARGO_PKG_VERSION").to_string(), fingerprint: D::FINGERPRINT.to_string(), database: Some(D::DIALECT) },
368            Ok(Request::Lex { sql, dialect }) => match lex::lex(&sql, dialect) {
369                Ok(lexed) => Response::Lexed { lexed },
370                Err(e) => Response::Error { message: e.message },
371            },
372            Ok(Request::Config { text }) => match crate::config::parse(&text) {
373                Ok(config) => Response::Config { config },
374                Err(error) => Response::ConfigError { error },
375            },
376            Ok(Request::Analyze { sql, mut answers, .. }) => {
377                D::unbundle(&mut answers);
378                match D::round(&sql, &answers) {
379                    Response::Analysis { mut analysis } => {
380                        analysis.comment = crate::comment::prose(&sql, D::DIALECT);
381                        Response::Analysis { analysis }
382                    }
383                    other => other,
384                }
385            }
386            Err(e) => Response::Error { message: format!("bad request: {e}") },
387        },
388    };
389    serde_json::to_string(&response).expect("response serializes")
390}