pub mod advice;
pub mod catalog;
pub mod grants;
pub mod kinds;
pub mod map;
pub mod names;
pub mod query;
use kinds::Kind;
use query::{Scope, Statement};
use crate::error::{Category, Failure, Result};
use crate::output::envelope::{Gap, Row};
use crate::sql::ident;
use mysql_async::Conn;
use serde_json::{json, Value};
#[derive(Debug, Clone, Copy)]
pub struct Ceilings {
pub map: map::Budget,
pub search_rows: usize,
pub ranked_objects: usize,
pub countable_rows: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DefinitionKind {
Table,
View,
Procedure,
Function,
Trigger,
Event,
Sequence,
}
impl DefinitionKind {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Table => "table",
Self::View => "view",
Self::Procedure => "procedure",
Self::Function => "function",
Self::Trigger => "trigger",
Self::Event => "event",
Self::Sequence => "sequence",
}
}
#[must_use]
pub fn parse(name: &str) -> Option<Self> {
[
Self::Table,
Self::View,
Self::Procedure,
Self::Function,
Self::Trigger,
Self::Event,
Self::Sequence,
]
.into_iter()
.find(|kind| kind.as_str() == name)
}
const fn keyword(self) -> &'static str {
match self {
Self::Table => "TABLE",
Self::View => "VIEW",
Self::Procedure => "PROCEDURE",
Self::Function => "FUNCTION",
Self::Trigger => "TRIGGER",
Self::Event => "EVENT",
Self::Sequence => "SEQUENCE",
}
}
}
pub async fn definition(
connection: &mut Conn,
kind: DefinitionKind,
database: &str,
name: &str,
) -> Result<Value> {
let target = ident::quote_qualified(&[database, name])?;
let statement = Statement {
text: format!("SHOW CREATE {} {target}", kind.keyword()),
values: Vec::new(),
};
let rows = query::run(connection, &statement).await?;
let written = rows
.first()
.and_then(|row| {
row.iter()
.find(|(key, _)| key.starts_with("Create") || key.starts_with("SQL Original"))
.map(|(_, value)| value.clone())
})
.ok_or_else(|| {
Failure::absence(
"schema.no_definition",
format!("the server wrote out no definition for `{database}`.`{name}`"),
)
.with_detail("detail", format!("{database}.{name}"))
.with_hint("confirm the object exists and the credential may read its definition")
})?;
Ok(json!({
"kind": kind.as_str(),
"database": database,
"name": name,
"definition": written,
}))
}
pub async fn kind_of(connection: &mut Conn, database: &str, name: &str) -> Result<DefinitionKind> {
let scope = Scope::on_table(Some(database.to_owned()), Some(name.to_owned()));
for (kind, definition) in [
(Kind::Table, DefinitionKind::Table),
(Kind::View, DefinitionKind::View),
(Kind::Sequence, DefinitionKind::Sequence),
(Kind::Event, DefinitionKind::Event),
] {
let mut narrowed = scope.clone();
if kind.descriptor().table_column.is_none() {
narrowed.table = None;
narrowed.name_pattern = Some(name.to_owned());
}
if !query::read(connection, kind.descriptor(), &narrowed)
.await?
.is_empty()
{
return Ok(definition);
}
}
let by_name = by_name(database, name);
let routines = query::read(connection, Kind::Routine.descriptor(), &by_name).await?;
if let Some(kind) = routines.first().and_then(routine_kind) {
return Ok(kind);
}
let triggers = query::read(connection, Kind::Trigger.descriptor(), &by_name).await?;
if triggers.is_empty() {
return Err(
Failure::absence("schema.unknown_object", format!("`{name}`"))
.with_detail("detail", format!("`{name}`"))
.with_detail("kind", "object-in-database")
.with_detail("database", format!("`{database}`"))
.with_detail("reason", "kind")
.with_hint("name the kind with --kind, or list the database first"),
);
}
Ok(DefinitionKind::Trigger)
}
fn by_name(database: &str, name: &str) -> Scope {
Scope {
database: Some(database.to_owned()),
name_pattern: Some(name.to_owned()),
..Scope::default()
}
}
fn routine_kind(row: &Row) -> Option<DefinitionKind> {
match row.get("type").and_then(Value::as_str)? {
"FUNCTION" => Some(DefinitionKind::Function),
"PROCEDURE" => Some(DefinitionKind::Procedure),
_ => None,
}
}
pub async fn exact_count(
connection: &mut Conn,
database: &str,
table: &str,
ceiling: u64,
) -> Result<Value> {
let target = ident::quote_qualified(&[database, table])?;
let estimate = estimated_rows(connection, database, table).await?;
if estimate > ceiling {
return Err(Failure::limit(
"schema.count_too_large",
format!(
"`{database}`.`{table}` is estimated at {estimate} rows and the ceiling is {ceiling}"
),
)
.with_detail("detail", format!("{estimate} > {ceiling}"))
.with_hint("raise the ceiling deliberately, or use `schema stats` for the estimate"));
}
let started = std::time::Instant::now();
let rows = query::run(
connection,
&Statement {
text: format!("SELECT COUNT(*) AS `rows` FROM {target}"),
values: Vec::new(),
},
)
.await?;
let elapsed = started.elapsed();
Ok(json!({
"database": database,
"table": table,
"rows": rows.first().and_then(|row| row.get("rows")).cloned().unwrap_or(Value::Null),
"exact": true,
"estimated": false,
"elapsed_ms": u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX),
}))
}
async fn estimated_rows(connection: &mut Conn, database: &str, table: &str) -> Result<u64> {
let rows = query::read(
connection,
Kind::Statistic.descriptor(),
&Scope::on_table(Some(database.to_owned()), Some(table.to_owned())),
)
.await?;
Ok(rows
.first()
.and_then(|row| row.get("estimated_rows"))
.and_then(Value::as_u64)
.unwrap_or_default())
}
#[must_use]
pub fn missing_space(rows: &[Row]) -> Option<Gap> {
let blind: Vec<&str> = rows
.iter()
.filter(|row| row.get("total_bytes").is_none_or(Value::is_null))
.filter_map(|row| row.get("database").and_then(Value::as_str))
.collect();
(!blind.is_empty()).then(|| {
Gap::new(
blind.join(", "),
"no_space_figure",
"the catalog keeps no space figure for these databases, which is not the same as zero",
)
})
}
pub fn searched_kinds(asked: &[String]) -> Result<Vec<Kind>> {
if asked.is_empty() {
return Ok(kinds::SEARCHABLE.to_vec());
}
asked
.iter()
.map(|name| {
Kind::parse(name).ok_or_else(|| {
let kinds = kinds::SEARCHABLE
.iter()
.map(|kind| kind.as_str())
.collect::<Vec<_>>()
.join(", ");
Failure::usage("schema.unknown_kind", format!("`{name}`"))
.with_detail("detail", format!("`{name}`"))
.with_detail("reason", "searched")
.with_hint(format!("the kinds searched are: {kinds}"))
.with_detail("kinds", kinds)
})
})
.collect()
}
pub async fn search(
connection: &mut Conn,
pattern: &str,
database: Option<&str>,
kinds: &[Kind],
ceiling: usize,
detailed: bool,
) -> Result<(Vec<Row>, Vec<Gap>)> {
let mut found = Vec::new();
let mut gaps = Vec::new();
for kind in kinds {
let scope = Scope {
database: database.map(ToOwned::to_owned),
name_pattern: Some(pattern.to_owned()),
limit: Some(ceiling),
detailed,
..Scope::default()
};
match query::read(connection, kind.descriptor(), &scope).await {
Ok(rows) => {
if rows.len() >= ceiling {
gaps.push(Gap::new(
kind.as_str(),
"ceiling",
format!("the search stopped at {ceiling} matches of this kind"),
));
}
found.extend(rows.into_iter().map(|row| tagged(*kind, row)));
}
Err(failure) if failure.category() == Category::Permission => {
gaps.push(Gap::new(
kind.as_str(),
"permission",
format!(
"the credential may not read this catalog: {}",
failure.message()
),
));
}
Err(failure) => return Err(failure),
}
}
Ok((found, gaps))
}
fn tagged(kind: Kind, row: Row) -> Row {
let mut tagged = Row::new();
tagged.insert("kind".to_owned(), json!(kind.as_str()));
tagged.extend(row);
tagged
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_published_kind_name_resolves_back_to_its_kind() {
assert_eq!(DefinitionKind::parse("table"), Some(DefinitionKind::Table));
assert_eq!(
DefinitionKind::parse("function"),
Some(DefinitionKind::Function)
);
assert_eq!(DefinitionKind::parse("materialised"), None);
}
#[test]
fn a_definition_target_is_always_quoted() {
let target = ident::quote_qualified(&["shop", "a`; DROP TABLE users; --"]).expect("quotes");
let text = format!("SHOW CREATE {} {target}", DefinitionKind::Table.keyword());
assert!(
text.starts_with("SHOW CREATE TABLE `shop`.`a``; DROP"),
"{text}"
);
assert!(text.ends_with('`'), "the name is closed: {text}");
}
#[test]
fn an_unwritable_name_never_reaches_a_definition_statement() {
let failure = ident::quote_qualified(&["shop", "bad\nname"]).expect_err("refuses");
assert_eq!(failure.code(), "ident.control_character");
}
#[test]
fn a_searched_row_says_what_kind_it_is() {
let mut row = Row::new();
row.insert("name".to_owned(), json!("orders"));
let tagged = tagged(Kind::Table, row);
assert_eq!(
tagged.get_index(0).map(|(key, _)| key.as_str()),
Some("kind")
);
assert_eq!(tagged["kind"], json!("table"));
}
#[test]
fn a_routine_row_says_whether_it_returns_a_value() {
let mut function = Row::new();
function.insert("type".to_owned(), json!("FUNCTION"));
assert_eq!(routine_kind(&function), Some(DefinitionKind::Function));
let mut procedure = Row::new();
procedure.insert("type".to_owned(), json!("PROCEDURE"));
assert_eq!(routine_kind(&procedure), Some(DefinitionKind::Procedure));
assert_eq!(routine_kind(&Row::new()), None);
}
#[test]
fn a_search_with_no_kinds_looks_through_them_all() {
assert_eq!(
searched_kinds(&[]).expect("all kinds"),
kinds::SEARCHABLE.to_vec()
);
}
#[test]
fn a_kind_outside_the_published_set_is_refused() {
let failure = searched_kinds(&["nonexistent".to_owned()]).expect_err("must refuse");
assert_eq!(failure.code(), "schema.unknown_kind");
assert_eq!(failure.exit_number().code(), 2);
}
#[test]
fn a_named_kind_narrows_the_search() {
assert_eq!(
searched_kinds(&["table".to_owned(), "view".to_owned()]).expect("named kinds"),
vec![Kind::Table, Kind::View]
);
}
#[test]
fn a_database_with_no_space_figure_is_declared() {
let mut blind = Row::new();
blind.insert("database".to_owned(), json!("shop"));
blind.insert("total_bytes".to_owned(), Value::Null);
let gap = missing_space(&[blind]).expect("declared");
assert_eq!(gap.cause, "no_space_figure");
assert_eq!(gap.object, "shop");
let mut known = Row::new();
known.insert("database".to_owned(), json!("shop"));
known.insert("total_bytes".to_owned(), json!(4096));
assert!(missing_space(&[known]).is_none());
}
}