use crate::database::Database;
use crate::dialect::Dialect;
use crate::lex;
use crate::types::{self, Cardinality, DialectVersion, ResultRows, StatementDescriptor, StatementKind, Type};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
#[derive(Debug, Deserialize)]
#[serde(tag = "op", rename_all = "camelCase", bound(deserialize = "D: DeserializeOwned"))]
pub enum Request<D> {
Ping,
Lex { sql: String, dialect: Dialect },
Config { text: String },
Analyze {
sql: String,
dialect: Dialect,
#[serde(default)]
answers: Answers<D>,
},
}
pub trait Describe: DeserializeOwned + Clone + std::fmt::Debug + Send + Sync + 'static {}
impl<T: DeserializeOwned + Clone + std::fmt::Debug + Send + Sync + 'static> Describe for T {}
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum Answer<D> {
Describe {
#[serde(alias = "mysql")]
describe: D,
},
Rows { rows: Vec<Vec<Value>> },
Error { error: DbError },
}
pub type Answers<D> = HashMap<String, Answer<D>>;
#[derive(Debug, Clone, Deserialize)]
pub enum NoDescribe {}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DbError {
pub message: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub position: Option<usize>,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum Need {
Describe { id: String, sql: String },
Query { id: String, sql: String, params: Vec<Value>, scope: Scope },
}
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Scope {
Session,
Statement,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Diagnostic {
pub message: String,
pub start: usize,
pub length: usize,
pub code: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub server_code: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Param {
pub name: String,
#[serde(rename = "type")]
pub ty: Type,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub nullable: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub optional: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub comment: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schema: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cast: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub delimiter: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub members: Vec<Member>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Member {
pub written: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schema: Option<Value>,
}
impl Param {
pub fn new(name: impl Into<String>, ty: Type) -> Param {
Param { name: name.into(), ty, nullable: false, optional: false, comment: None, schema: None, cast: None, delimiter: None, members: Vec::new() }
}
pub fn descriptor(&self) -> types::Param {
types::Param { name: self.name.clone(), ty: self.ty.clone(), nullable: self.nullable, optional: self.optional, comment: self.comment.clone() }
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Column {
pub name: String,
#[serde(rename = "type")]
pub ty: Type,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub nullable: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub comment: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub delimiter: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub described: Option<String>,
}
impl Column {
pub fn new(name: impl Into<String>, ty: Type, nullable: bool) -> Column {
Column { name: name.into(), ty, nullable, comment: None, delimiter: None, described: None }
}
pub fn descriptor(&self) -> types::Field {
types::Field { comment: self.comment.clone(), ..types::Field::new(self.name.clone(), self.ty.clone(), self.nullable) }
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Analysis {
#[serde(skip_serializing_if = "Option::is_none")]
pub kind: Option<StatementKind>,
#[serde(skip_serializing_if = "Option::is_none")]
pub comment: Option<String>,
pub params: Vec<Param>,
pub columns: Vec<Column>,
pub cardinality: Cardinality,
#[serde(skip_serializing_if = "Option::is_none")]
pub cardinality_reason: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub key: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub unique: Vec<Vec<String>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub order: Vec<types::SortKey>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub ordered: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub value: bool,
pub rewritten: lex::Rewritten,
#[serde(skip_serializing_if = "Option::is_none")]
pub sql_mode: Option<lex::MysqlText>,
pub style: lex::Style,
pub diagnostics: Vec<Diagnostic>,
pub unresolved: Vec<String>,
#[serde(skip_serializing_if = "crate::structured::none_rewritten", serialize_with = "crate::structured::rewritten_only")]
pub structured: Vec<crate::structured::Info>,
#[serde(skip_serializing_if = "Option::is_none")]
pub errors: Option<crate::errors::Errors>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub capabilities: Option<types::Capabilities>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub read_only: bool,
#[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub domains: std::collections::BTreeMap<String, String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub notes: Vec<String>,
#[serde(skip_serializing_if = "reads_no_body")]
pub tables: Option<crate::fresh::Tables>,
}
fn reads_no_body(tables: &Option<crate::fresh::Tables>) -> bool {
tables.as_ref().is_none_or(|t| t.functions.is_empty())
}
impl Analysis {
pub fn descriptor(&self, sql: &str, dialect: DialectVersion) -> StatementDescriptor {
StatementDescriptor {
schema: types::SCHEMA.to_string(),
dialect,
sql: self.rewritten.sql.clone(),
kind: self.kind,
comment: self.comment.clone(),
params: self.params.iter().map(Param::descriptor).collect(),
result: ResultRows::new(self.cardinality, self.columns.iter().map(Column::descriptor).collect(), self.unique.clone(), self.order.clone()),
capabilities: self.capabilities.clone(),
diagnostics: self.diagnostics.iter().map(|d| {
let start = utf16_offset(sql, d.start);
types::Diagnostic { message: d.message.clone(), start, end: utf16_offset(sql, d.start + d.length).max(start), code: d.server_code.clone() }
}).collect(),
}
}
}
pub fn utf16_offset(text: &str, byte: usize) -> usize {
let mut at = byte.min(text.len());
while !text.is_char_boundary(at) {
at -= 1;
}
text[..at].encode_utf16().count()
}
#[derive(Debug, Serialize)]
#[serde(tag = "status", rename_all = "camelCase")]
pub enum Response {
Ok {
version: String,
fingerprint: String,
#[serde(skip_serializing_if = "Option::is_none")]
database: Option<Dialect>,
},
Lexed { lexed: lex::Lexed },
Config { config: crate::config::Project },
ConfigError { error: crate::config::ConfigError },
Need { needs: Vec<Need> },
Analysis { analysis: Analysis },
Error { message: String },
}
#[derive(Debug, Deserialize)]
struct Head {
#[serde(default)]
op: String,
#[serde(default)]
dialect: Option<Dialect>,
}
pub fn dialect_of(request: &str) -> Option<Dialect> {
serde_json::from_str::<Head>(request).ok()?.dialect
}
pub fn call<D: Database>(request: &str) -> String {
crate::stack::run(|| call_here::<D>(request))
}
fn call_here<D: Database>(request: &str) -> String {
let head = serde_json::from_str::<Head>(request).ok();
let response = match head {
Some(Head { op, dialect: Some(other) }) if op == "analyze" && other != D::DIALECT => {
Response::Error { message: format!("this engine reads {} statements, not {} ones", D::DIALECT.name(), other.name()) }
}
_ => match serde_json::from_str::<Request<D::Describe>>(request) {
Ok(Request::Ping) => Response::Ok { version: env!("CARGO_PKG_VERSION").to_string(), fingerprint: D::FINGERPRINT.to_string(), database: Some(D::DIALECT) },
Ok(Request::Lex { sql, dialect }) => match lex::lex(&sql, dialect) {
Ok(lexed) => Response::Lexed { lexed },
Err(e) => Response::Error { message: e.message },
},
Ok(Request::Config { text }) => match crate::config::parse(&text) {
Ok(config) => Response::Config { config },
Err(error) => Response::ConfigError { error },
},
Ok(Request::Analyze { sql, mut answers, .. }) => {
D::unbundle(&mut answers);
match D::round(&sql, &answers) {
Response::Analysis { mut analysis } => {
analysis.comment = crate::comment::prose(&sql, D::DIALECT);
Response::Analysis { analysis }
}
other => other,
}
}
Err(e) => Response::Error { message: format!("bad request: {e}") },
},
};
serde_json::to_string(&response).expect("response serializes")
}