pub mod temporal;
use crate::error::{Failure, Result};
use crate::output::{Envelope, Gap, Row};
use crate::serverinfo::{cell, fetch, text_of};
use crate::sql::ident;
use mysql_async::{params, Conn, Params};
use serde_json::{json, Value};
const VERSIONED: &str = "SYSTEM VERSIONED";
const LISTING: &str = "SELECT TABLE_NAME, TABLE_TYPE, TABLE_ROWS, DATA_LENGTH \
FROM information_schema.TABLES \
WHERE TABLE_SCHEMA = :database \
AND TABLE_TYPE IN ('BASE TABLE', 'SYSTEM VERSIONED') \
ORDER BY TABLE_NAME";
const KIND_OF_TABLE: &str = "SELECT TABLE_TYPE \
FROM information_schema.TABLES \
WHERE TABLE_SCHEMA = :database AND TABLE_NAME = :table";
const PERIOD_CLAUSE: &str = "PERIOD FOR SYSTEM_TIME";
const IMPLICIT_START: &str = "row_start";
const IMPLICIT_END: &str = "row_end";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Period {
pub database: String,
pub table: String,
pub start_column: String,
pub end_column: String,
}
pub async fn tables(
connection: &mut Conn,
named: Option<&str>,
session_database: Option<&str>,
) -> Result<Envelope> {
let database = resolve_database(named, session_database)?;
confirm_database_exists(connection, &database).await?;
let source = fetch(
connection,
LISTING,
params! { "database" => database.clone() },
)
.await?;
let mut rows = Vec::with_capacity(source.len());
let mut gaps = Vec::new();
for row in &source {
rows.push(describe(connection, &database, row, &mut gaps).await);
}
let mut envelope = Envelope::new(
"history tables",
json!({ "database": database, "rows": rows }),
);
for gap in gaps {
envelope = envelope.with_gap(gap);
}
Ok(envelope)
}
async fn describe(connection: &mut Conn, database: &str, row: &Row, gaps: &mut Vec<Gap>) -> Row {
let name = text_of(cell(row, "TABLE_NAME"));
let versioned = text_of(cell(row, "TABLE_TYPE")).eq_ignore_ascii_case(VERSIONED);
let earliest = if versioned {
match earliest_instant(connection, database, &name).await {
Ok(value) => value,
Err(failure) => {
gaps.push(Gap::new(
name.clone(),
"earliest_instant_unreadable",
failure.message().to_owned(),
));
Value::Null
}
}
} else {
Value::Null
};
let mut shaped = Row::new();
shaped.insert("database".to_owned(), json!(database));
shaped.insert("name".to_owned(), json!(name));
shaped.insert("versioned".to_owned(), json!(versioned));
shaped.insert("earliest_instant".to_owned(), earliest);
shaped.insert(
"rows".to_owned(),
cell(row, "TABLE_ROWS").cloned().unwrap_or(Value::Null),
);
shaped.insert(
"bytes".to_owned(),
cell(row, "DATA_LENGTH").cloned().unwrap_or(Value::Null),
);
shaped
}
async fn earliest_instant(connection: &mut Conn, database: &str, table: &str) -> Result<Value> {
let period = read_period(connection, database, table).await?;
let sql = format!(
"SELECT MIN({start}) FROM {qualified} FOR SYSTEM_TIME ALL",
start = ident::quote(&period.start_column)?,
qualified = ident::quote_qualified(&[database, table])?,
);
let rows = fetch(connection, &sql, Params::Empty).await?;
Ok(rows
.first()
.and_then(|row| row.values().next())
.cloned()
.unwrap_or(Value::Null))
}
pub async fn read_period(connection: &mut Conn, database: &str, table: &str) -> Result<Period> {
let kind = fetch(
connection,
KIND_OF_TABLE,
params! { "database" => database.to_owned(), "table" => table.to_owned() },
)
.await?;
let keeps_history = kind
.first()
.is_some_and(|row| text_of(cell(row, "TABLE_TYPE")).eq_ignore_ascii_case(VERSIONED));
if !keeps_history {
return Err(not_versioned(database, table));
}
let ddl = definition_of(connection, database, table).await?;
let (start_column, end_column) = period_columns(ddl.as_deref());
Ok(Period {
database: database.to_owned(),
table: table.to_owned(),
start_column,
end_column,
})
}
async fn definition_of(
connection: &mut Conn,
database: &str,
table: &str,
) -> Result<Option<String>> {
let sql = format!(
"SHOW CREATE TABLE {qualified}",
qualified = ident::quote_qualified(&[database, table])?,
);
let rows = fetch(connection, &sql, Params::Empty).await?;
Ok(rows.first().and_then(|row| {
row.iter()
.find(|(name, _)| name.eq_ignore_ascii_case("Create Table"))
.map(|(_, value)| text_of(Some(value)))
}))
}
#[must_use]
fn period_columns(definition: Option<&str>) -> (String, String) {
let named = definition.and_then(|text| {
let opened = text.find(PERIOD_CLAUSE)? + PERIOD_CLAUSE.len();
let mut names = quoted_names(&text[opened..]);
let start = names.next()?;
let end = names.next()?;
Some((start, end))
});
named.unwrap_or_else(|| (IMPLICIT_START.to_owned(), IMPLICIT_END.to_owned()))
}
fn quoted_names(tail: &str) -> impl Iterator<Item = String> + '_ {
let mut rest = tail;
std::iter::from_fn(move || {
let opening = rest.find('`')?;
if rest[..opening].contains(')') {
return None;
}
let mut name = String::new();
let mut walk = rest[opening + 1..].char_indices();
while let Some((at, letter)) = walk.next() {
if letter != '`' {
name.push(letter);
continue;
}
if rest[opening + 1 + at + 1..].starts_with('`') {
name.push('`');
walk.next();
continue;
}
rest = &rest[opening + 1 + at + 1..];
return Some(name);
}
None
})
}
#[must_use]
pub fn not_versioned(database: &str, table: &str) -> Failure {
Failure::validation(
"validation.table_keeps_no_history",
format!("the table `{database}`.`{table}` keeps no version history"),
)
.with_detail("detail", format!("{database}.{table}"))
.with_hint(
"run `history tables` to see which tables keep one, or turn versioning on for this table",
)
}
pub fn resolve_database(named: Option<&str>, in_force: Option<&str>) -> Result<String> {
named.or(in_force).map(ToOwned::to_owned).ok_or_else(|| {
Failure::absence(
"absence.no_database_in_force",
"no database was named and the destination has none in force",
)
.with_hint("name one with --database")
})
}
async fn confirm_database_exists(connection: &mut Conn, database: &str) -> Result<()> {
let rows = fetch(
connection,
"SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = :database",
params! { "database" => database.to_owned() },
)
.await?;
if rows.is_empty() {
return Err(Failure::absence(
"absence.unknown_database",
format!("the database `{database}` does not exist on this destination"),
)
.with_detail("detail", database)
.with_hint("run `schema databases` to see the databases this credential can reach"));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_table_keeping_no_history_is_refused_with_a_way_forward() {
let failure = not_versioned("loja", "vendas");
assert_eq!(failure.exit_number().code(), 3);
assert!(failure.message().contains("vendas"));
assert!(failure
.hint()
.is_some_and(|hint| hint.contains("history tables")));
}
#[test]
fn the_named_database_outranks_the_one_in_force() {
assert_eq!(
resolve_database(Some("loja"), Some("sales")).expect("named wins"),
"loja"
);
assert_eq!(
resolve_database(None, Some("sales")).expect("in force serves"),
"sales"
);
let failure = resolve_database(None, None).expect_err("nothing to work on");
assert_eq!(failure.exit_number().code(), 8);
}
#[test]
fn a_versioned_table_is_recognised_whatever_case_the_server_used() {
assert!("System Versioned".eq_ignore_ascii_case(VERSIONED));
assert!(!"BASE TABLE".eq_ignore_ascii_case(VERSIONED));
}
#[test]
fn a_declared_pair_comes_from_the_definition() {
let ddl = "CREATE TABLE `prices` (\n `id` int(11) NOT NULL,\n \
`st` timestamp(6) GENERATED ALWAYS AS ROW START,\n \
`en` timestamp(6) GENERATED ALWAYS AS ROW END,\n \
PRIMARY KEY (`id`,`en`),\n \
PERIOD FOR SYSTEM_TIME (`st`, `en`)\n) WITH SYSTEM VERSIONING";
assert_eq!(
period_columns(Some(ddl)),
("st".to_owned(), "en".to_owned())
);
}
#[test]
fn an_undeclared_pair_falls_back_to_the_implied_names() {
let ddl = "CREATE TABLE `prices` (\n `sku` varchar(32) NOT NULL,\n \
PRIMARY KEY (`sku`)\n) ENGINE=InnoDB WITH SYSTEM VERSIONING";
assert_eq!(
period_columns(Some(ddl)),
(IMPLICIT_START.to_owned(), IMPLICIT_END.to_owned())
);
}
#[test]
fn a_missing_definition_still_answers_with_the_implied_names() {
assert_eq!(
period_columns(None),
(IMPLICIT_START.to_owned(), IMPLICIT_END.to_owned())
);
}
#[test]
fn a_name_carrying_the_quoting_mark_is_not_torn_in_half() {
let ddl = "PERIOD FOR SYSTEM_TIME (`od``d`, `en,d`)";
assert_eq!(
period_columns(Some(ddl)),
("od`d".to_owned(), "en,d".to_owned())
);
}
#[test]
fn a_half_written_clause_is_not_trusted() {
assert_eq!(
period_columns(Some("PERIOD FOR SYSTEM_TIME (`st`)")),
(IMPLICIT_START.to_owned(), IMPLICIT_END.to_owned())
);
}
}