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    /// The column's type as the server names it, on one line (`DateTime64(3, 'UTC')`), where a
188    /// result carries its columns' types with its rows, as ClickHouse's does: the run time holds
189    /// each result's against it, since a setting of the session that runs the statement can change
190    /// a type the analysis read. The format's field leaves it out.
191    #[serde(default, skip_serializing_if = "Option::is_none")]
192    pub described: Option<String>,
193}
194
195impl Column {
196    /// A column of `ty`, with nothing else known of it.
197    pub fn new(name: impl Into<String>, ty: Type, nullable: bool) -> Column {
198        Column { name: name.into(), ty, nullable, comment: None, delimiter: None, described: None }
199    }
200
201    /// The column as the format writes it: a field of the result's record.
202    pub fn descriptor(&self) -> types::Field {
203        types::Field { comment: self.comment.clone(), ..types::Field::new(self.name.clone(), self.ty.clone(), self.nullable) }
204    }
205}
206
207#[derive(Debug, Clone, Serialize)]
208#[serde(rename_all = "camelCase")]
209pub struct Analysis {
210    /// The statement's kind: one of the five, `other` for any other, absent when it did not parse.
211    #[serde(skip_serializing_if = "Option::is_none")]
212    pub kind: Option<StatementKind>,
213    /// The prose written in comments before the statement ([`crate::comment::leading`]).
214    #[serde(skip_serializing_if = "Option::is_none")]
215    pub comment: Option<String>,
216    pub params: Vec<Param>,
217    pub columns: Vec<Column>,
218    /// How many rows the statement returns.
219    pub cardinality: Cardinality,
220    /// Why the proof stopped short of `one`, when it did.
221    #[serde(skip_serializing_if = "Option::is_none")]
222    pub cardinality_reason: Option<String>,
223    /// The result key: output columns, by name, that identify each row of the result, since no two
224    /// rows the statement returns agree on all of them (a NULL counting as equal to another NULL).
225    /// Only for a result that can hold more than one row: `None` where the cardinality is `one` or
226    /// `at_most_one`, which says as much, and where no key is proven, which is always sound.
227    #[serde(skip_serializing_if = "Option::is_none")]
228    pub key: Option<Vec<String>>,
229    /// Every set of output columns no two rows agree on all of, as `key` is, none inside another,
230    /// and a table's primary key first where the result holds it. Empty where none is proven.
231    #[serde(default, skip_serializing_if = "Vec::is_empty")]
232    pub unique: Vec<Vec<String>>,
233    /// The columns of the result its ORDER BY sorts on, as far as its keys are such columns.
234    #[serde(default, skip_serializing_if = "Vec::is_empty")]
235    pub order: Vec<types::SortKey>,
236    /// Whether the statement's ORDER BY orders its rows totally: no two rows of any result tie on
237    /// every sort key, so the order is the same on every run. Only for a result that can hold more
238    /// than one row, as `key` is.
239    #[serde(skip_serializing_if = "std::ops::Not::not")]
240    pub ordered: bool,
241    /// Whether the result is its one column's values, not rows that hold them: the statement's one
242    /// column is an expression it gives no name, so the only name it has is one the database makes
243    /// up ([`crate::analysis::names`]).
244    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
245    pub value: bool,
246    pub rewritten: lex::Rewritten,
247    /// How the session the statement was read on reads MySQL's strings and double quotes, by its
248    /// `sql_mode`, where another mode would read the statement otherwise: its placeholders hold
249    /// only for a session that reads it so. Absent where every mode reads it alike, and on every
250    /// other database.
251    #[serde(skip_serializing_if = "Option::is_none")]
252    pub sql_mode: Option<lex::MysqlText>,
253    pub style: lex::Style,
254    pub diagnostics: Vec<Diagnostic>,
255    /// Paths inside JSON columns the engine could not type, for a message.
256    pub unresolved: Vec<String>,
257    /// Each structured parameter in insert position, with the lists of `rewritten` the run time
258    /// writes again for a call that leaves keys out ([`crate::structured`]); on the wire only
259    /// those that have lists (MySQL's), since a Postgres or SQLite statement copies its defaults.
260    #[serde(skip_serializing_if = "crate::structured::none_rewritten", serialize_with = "crate::structured::rewritten_only")]
261    pub structured: Vec<crate::structured::Info>,
262    /// The names each error the statement may raise can carry, where it runs only its database's
263    /// own code ([`crate::errors`]).
264    #[serde(skip_serializing_if = "Option::is_none")]
265    pub errors: Option<crate::errors::Errors>,
266    /// What running the statement may do, an upper bound ([`types::Capabilities`]); absent where
267    /// nothing is said.
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub capabilities: Option<types::Capabilities>,
270    /// Whether the engine finds nothing in the statement that could write, so that a caller may run it again after
271    /// a lost connection ([`crate::database::Database::read_only`]).
272    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
273    pub read_only: bool,
274    /// Each domain a type of the statement is named by, with the name of the base type it is made
275    /// from: a client decodes a domain's values as its base type's (a Postgres domain over
276    /// pgvector's `vector` comes as the vector's text), which the format leaves to the catalog.
277    #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
278    pub domains: std::collections::BTreeMap<String, String>,
279    /// What is worth saying of the statement but fails nothing, for a hover: the type check has no
280    /// level below an error.
281    #[serde(skip_serializing_if = "Vec::is_empty")]
282    pub notes: Vec<String>,
283    /// The tables the statement reads and writes, as its database's own parse names them
284    /// ([`crate::fresh::Tables`]). On the wire only where the analysis read a function's body,
285    /// whose tables a parse of the statement as written cannot give: so a server's analysis
286    /// carries them to its client.
287    #[serde(skip_serializing_if = "reads_no_body")]
288    pub tables: Option<crate::fresh::Tables>,
289}
290
291fn reads_no_body(tables: &Option<crate::fresh::Tables>) -> bool {
292    tables.as_ref().is_none_or(|t| t.functions.is_empty())
293}
294
295impl Analysis {
296    /// The statement as the format describes it ([`StatementDescriptor`]): `sql` is the statement
297    /// as it was written, which the diagnostics' offsets index, and `dialect` the database and
298    /// version the analysis read.
299    pub fn descriptor(&self, sql: &str, dialect: DialectVersion) -> StatementDescriptor {
300        StatementDescriptor {
301            schema: types::SCHEMA.to_string(),
302            dialect,
303            sql: self.rewritten.sql.clone(),
304            kind: self.kind,
305            comment: self.comment.clone(),
306            params: self.params.iter().map(Param::descriptor).collect(),
307            result: ResultRows::new(self.cardinality, self.columns.iter().map(Column::descriptor).collect(), self.unique.clone(), self.order.clone()),
308            capabilities: self.capabilities.clone(),
309            diagnostics: self.diagnostics.iter().map(|d| {
310                let start = utf16_offset(sql, d.start);
311                types::Diagnostic { message: d.message.clone(), start, end: utf16_offset(sql, d.start + d.length).max(start), code: d.server_code.clone() }
312            }).collect(),
313        }
314    }
315}
316
317/// The UTF-16 offset of the UTF-8 byte offset `byte` of `text`, as the format counts: a byte
318/// inside a character counts from the character's start, and one past the end at the end.
319pub fn utf16_offset(text: &str, byte: usize) -> usize {
320    let mut at = byte.min(text.len());
321    while !text.is_char_boundary(at) {
322        at -= 1;
323    }
324    text[..at].encode_utf16().count()
325}
326
327#[derive(Debug, Serialize)]
328#[serde(tag = "status", rename_all = "camelCase")]
329pub enum Response {
330    Ok {
331        version: String,
332        fingerprint: String,
333        /// The database whose statements this artifact reads.
334        #[serde(skip_serializing_if = "Option::is_none")]
335        database: Option<Dialect>,
336    },
337    Lexed { lexed: lex::Lexed },
338    Config { config: crate::config::Project },
339    ConfigError { error: crate::config::ConfigError },
340    Need { needs: Vec<Need> },
341    Analysis { analysis: Analysis },
342    Error { message: String },
343}
344
345/// What a request says before its answers are read: what a host that links several databases
346/// dispatches on, and what lets [`call`] refuse another database's statement by name.
347#[derive(Debug, Deserialize)]
348struct Head {
349    #[serde(default)]
350    op: String,
351    #[serde(default)]
352    dialect: Option<Dialect>,
353}
354
355/// The dialect a request names, if it names one it can be read for.
356pub fn dialect_of(request: &str) -> Option<Dialect> {
357    serde_json::from_str::<Head>(request).ok()?.dialect
358}
359
360/// One request in, one response out, both JSON text, for the database `D`: the only entry point
361/// of a database's artifact.
362pub fn call<D: Database>(request: &str) -> String {
363    crate::stack::run(|| call_here::<D>(request))
364}
365
366fn call_here<D: Database>(request: &str) -> String {
367    let head = serde_json::from_str::<Head>(request).ok();
368    let response = match head {
369        Some(Head { op, dialect: Some(other) }) if op == "analyze" && other != D::DIALECT => {
370            Response::Error { message: format!("this engine reads {} statements, not {} ones", D::DIALECT.name(), other.name()) }
371        }
372        _ => match serde_json::from_str::<Request<D::Describe>>(request) {
373            Ok(Request::Ping) => Response::Ok { version: env!("CARGO_PKG_VERSION").to_string(), fingerprint: D::FINGERPRINT.to_string(), database: Some(D::DIALECT) },
374            Ok(Request::Lex { sql, dialect }) => match lex::lex(&sql, dialect) {
375                Ok(lexed) => Response::Lexed { lexed },
376                Err(e) => Response::Error { message: e.message },
377            },
378            Ok(Request::Config { text }) => match crate::config::parse(&text) {
379                Ok(config) => Response::Config { config },
380                Err(error) => Response::ConfigError { error },
381            },
382            Ok(Request::Analyze { sql, mut answers, .. }) => {
383                D::unbundle(&mut answers);
384                match D::round(&sql, &answers) {
385                    Response::Analysis { mut analysis } => {
386                        analysis.comment = crate::comment::prose(&sql, D::DIALECT);
387                        Response::Analysis { analysis }
388                    }
389                    other => other,
390                }
391            }
392            Err(e) => Response::Error { message: format!("bad request: {e}") },
393        },
394    };
395    serde_json::to_string(&response).expect("response serializes")
396}