use super::kinds::{fields, Descriptor};
use crate::conn::OrFailure;
use crate::error::Result;
use crate::output::envelope::Row;
use crate::sql::ident;
use mysql_async::prelude::Queryable;
use mysql_async::{Conn, Params, Value as Wire};
use serde_json::Value;
#[derive(Debug, Clone, Default)]
pub struct Scope {
pub database: Option<String>,
pub table: Option<String>,
pub name_pattern: Option<String>,
pub detailed: bool,
pub limit: Option<usize>,
}
impl Scope {
#[must_use]
pub fn in_database(database: Option<String>) -> Self {
Self {
database,
..Self::default()
}
}
#[must_use]
pub fn on_table(database: Option<String>, table: Option<String>) -> Self {
Self {
database,
table,
..Self::default()
}
}
#[must_use]
pub const fn detailed(mut self, detailed: bool) -> Self {
self.detailed = detailed;
self
}
#[must_use]
pub const fn limited(mut self, limit: Option<usize>) -> Self {
self.limit = limit;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Statement {
pub text: String,
pub values: Vec<String>,
}
impl Statement {
#[must_use]
fn params(&self) -> Params {
Params::Positional(
self.values
.iter()
.map(|value| Wire::Bytes(value.clone().into_bytes()))
.collect(),
)
}
}
pub fn build(descriptor: &Descriptor, scope: &Scope) -> Result<Statement> {
let mut projection = String::new();
for (position, field) in fields(descriptor, scope.detailed).iter().enumerate() {
if position > 0 {
projection.push_str(", ");
}
projection.push_str(field.source);
projection.push_str(" AS ");
projection.push_str(&ident::quote(field.alias)?);
}
let mut text = format!("SELECT {projection} FROM {}", descriptor.source);
let mut conditions: Vec<String> = descriptor
.predicate
.map(ToOwned::to_owned)
.into_iter()
.collect();
let mut values = Vec::new();
push_equality(
&mut conditions,
&mut values,
descriptor.database_column,
scope.database.as_deref(),
)?;
push_equality(
&mut conditions,
&mut values,
descriptor.table_column,
scope.table.as_deref(),
)?;
if let Some(pattern) = scope.name_pattern.as_deref() {
conditions.push(format!("{} LIKE ?", descriptor.name_column));
values.push(pattern.to_owned());
}
if !conditions.is_empty() {
text.push_str(" WHERE ");
text.push_str(&conditions.join(" AND "));
}
if let Some(group) = descriptor.group_by {
text.push_str(" GROUP BY ");
text.push_str(group);
}
text.push_str(" ORDER BY ");
text.push_str(descriptor.order_by);
if let Some(limit) = scope.limit {
use std::fmt::Write as _;
let _ = write!(text, " LIMIT {limit}");
}
Ok(Statement { text, values })
}
fn push_equality(
conditions: &mut Vec<String>,
values: &mut Vec<String>,
column: Option<&'static str>,
supplied: Option<&str>,
) -> Result<()> {
let (Some(column), Some(supplied)) = (column, supplied) else {
return Ok(());
};
ident::quote(supplied)?;
conditions.push(format!("{column} = ?"));
values.push(supplied.to_owned());
Ok(())
}
pub async fn read(
connection: &mut Conn,
descriptor: &Descriptor,
scope: &Scope,
) -> Result<Vec<Row>> {
let statement = build(descriptor, scope)?;
run(connection, &statement).await
}
pub async fn run(connection: &mut Conn, statement: &Statement) -> Result<Vec<Row>> {
let rows: Vec<mysql_async::Row> = connection
.exec(statement.text.clone(), statement.params())
.await
.or_failure()?;
rows.iter().map(convert_row).collect()
}
fn convert_row(row: &mysql_async::Row) -> Result<Row> {
let columns = row.columns();
let mut converted = Row::new();
for (index, column) in columns.iter().enumerate() {
let value = row.as_ref(index).cloned().unwrap_or(Wire::NULL);
converted.insert(
column.name_str().into_owned(),
crate::types::value::convert(&value, column, &crate::types::Conversion::stable())?,
);
}
Ok(converted)
}
pub async fn setting(connection: &mut Conn, statement: &'static str) -> Result<Option<Value>> {
let found: Option<String> = connection.query_first(statement).await.or_failure()?;
Ok(found.map(Value::from))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::introspect::kinds::Kind;
fn text_for(kind: Kind, scope: &Scope) -> String {
build(kind.descriptor(), scope).expect("builds").text
}
#[test]
fn a_supplied_name_is_bound_and_never_written_into_the_statement() {
let scope = Scope::in_database(Some("shop`; DROP TABLE users; --".to_owned()));
let statement = build(Kind::Table.descriptor(), &scope).expect("builds");
assert!(
!statement.text.contains("DROP TABLE"),
"the name reached the statement text: {}",
statement.text
);
assert_eq!(
statement.values,
vec!["shop`; DROP TABLE users; --".to_owned()]
);
assert!(statement.text.contains("TABLE_SCHEMA = ?"));
}
#[test]
fn an_unwritable_name_is_refused_before_the_server_is_reached() {
let scope = Scope::in_database(Some("bad\nname".to_owned()));
let failure = build(Kind::Table.descriptor(), &scope).expect_err("must refuse");
assert_eq!(failure.code(), "ident.control_character");
}
#[test]
fn the_condition_of_a_kind_survives_the_scope() {
let text = text_for(Kind::Sequence, &Scope::in_database(Some("shop".to_owned())));
assert!(text.contains("TABLE_TYPE = 'SEQUENCE'"), "{text}");
assert!(text.contains("TABLE_SCHEMA = ?"), "{text}");
}
#[test]
fn depth_changes_the_fields_and_not_the_scope() {
let short = text_for(Kind::Table, &Scope::default());
let detailed = text_for(Kind::Table, &Scope::default().detailed(true));
assert!(detailed.len() > short.len());
assert!(short.contains("`name`") && detailed.contains("`engine`"));
}
#[test]
fn every_reading_is_ordered() {
for kind in [Kind::Database, Kind::Table, Kind::Column, Kind::Index] {
assert!(text_for(kind, &Scope::default()).contains(" ORDER BY "));
}
}
#[test]
fn a_grouped_kind_groups_before_it_orders() {
let text = text_for(Kind::DatabaseSpace, &Scope::default());
let group = text.find(" GROUP BY ").expect("groups");
let order = text.find(" ORDER BY ").expect("orders");
assert!(group < order, "{text}");
}
#[test]
fn a_ceiling_reaches_the_server() {
let text = text_for(Kind::ObjectSpace, &Scope::default().limited(Some(10)));
assert!(text.ends_with(" LIMIT 10"), "{text}");
}
#[test]
fn a_pattern_narrows_by_name_and_travels_as_a_value() {
let mut scope = Scope::in_database(None);
scope.name_pattern = Some("ped%".to_owned());
let statement = build(Kind::Table.descriptor(), &scope).expect("builds");
assert!(statement.text.contains("TABLE_NAME LIKE ?"));
assert_eq!(statement.values, vec!["ped%".to_owned()]);
}
#[test]
fn every_alias_is_quoted() {
let text = text_for(Kind::Column, &Scope::default());
assert!(text.contains(" AS `table`"), "{text}");
assert!(text.contains(" AS `key`"), "{text}");
}
}