use super::args::{object_of, pattern_of, table_of, unknown_kind};
use super::{advice_wanted, Target};
use crate::cli::schema::{
AdvisableTableArgs, DdlArgs, Detail, DetailedTableArgs, MapArgs, ScopeArgs, SearchArgs,
SizeArgs, TableArgs, TablesArgs, ViewsArgs,
};
use crate::conn::Session;
use crate::error::{Failure, Result};
use crate::introspect::kinds::Kind;
use crate::introspect::names;
use crate::introspect::query::{self, Scope};
use crate::introspect::{advice, map, DefinitionKind};
use crate::output::envelope::Gap;
use crate::output::Envelope;
use serde_json::{json, Value};
async fn locate(
session: &mut Session,
database: Option<String>,
table: Option<String>,
) -> Result<(Scope, Vec<Value>)> {
let mut declared = Vec::new();
let (database, table) = match table {
None => (database, None),
Some(written) => {
let split = names::split(&written);
if split.overrides(database.as_deref()) {
declared.push(json!({
"asked": database,
"actual": split.database,
"kind": "database_from_name",
}));
}
(split.database_or(database), Some(split.name))
}
};
let Some(database) = database else {
return Ok((Scope::on_table(None, table), declared));
};
let found = names::resolve_database(session.connection(), &database).await?;
if found.differs_only_by_case() {
declared.push(json!({"asked": found.asked, "actual": found.actual, "kind": "database"}));
}
let database = found.actual;
let Some(table) = table else {
return Ok((Scope::in_database(Some(database)), declared));
};
let found = names::resolve_table(session.connection(), &database, &table).await?;
if found.differs_only_by_case() {
declared.push(json!({"asked": found.asked, "actual": found.actual, "kind": "table"}));
}
Ok((
Scope::on_table(Some(database), Some(found.actual)),
declared,
))
}
async fn annotate(session: &mut Session, data: &mut Value, declared: Vec<Value>) -> Result<()> {
data["name_case"] = json!(names::name_case(session.connection()).await?.as_str());
if !declared.is_empty() {
data["resolved_names"] = json!(declared);
}
Ok(())
}
pub(super) async fn listing(
name: &'static str,
kind: Kind,
session: &mut Session,
database: Option<String>,
table: Option<String>,
detailed: bool,
) -> Result<Envelope> {
let (scope, declared) = locate(session, database, table).await?;
let rows = query::read(
session.connection(),
kind.descriptor(),
&scope.detailed(detailed),
)
.await?;
let mut data = json!({ "rows": rows });
annotate(session, &mut data, declared).await?;
Ok(Envelope::new(name, data))
}
pub(super) async fn in_database(
name: &'static str,
kind: Kind,
args: &ScopeArgs,
session: &mut Session,
target: &Target,
) -> Result<Envelope> {
let database = target.database.clone();
listing(
name,
kind,
session,
database,
None,
Detail::or_default(args.detail, Detail::Summary),
)
.await
}
pub(super) async fn on_table(
name: &'static str,
kind: Kind,
args: &DetailedTableArgs,
detailed: bool,
session: &mut Session,
target: &Target,
) -> Result<Envelope> {
let table = table_of(args.table.as_ref())?;
let database = target.database.clone();
listing(name, kind, session, database, Some(table), detailed).await
}
pub(super) async fn tables(
name: &'static str,
args: &TablesArgs,
session: &mut Session,
target: &Target,
) -> Result<Envelope> {
let database = if args.all_databases {
None
} else {
target.database.clone()
};
listing(
name,
Kind::Table,
session,
database,
None,
Detail::or_default(args.detail, Detail::Summary),
)
.await
}
pub(super) async fn advised(
name: &'static str,
kind: Kind,
args: &AdvisableTableArgs,
session: &mut Session,
target: &Target,
) -> Result<Envelope> {
let database = target.database.clone();
let (scope, declared) = locate(session, database, args.table.clone()).await?;
let deep = Detail::or_default(args.detail, Detail::Summary);
let rows = query::read(
session.connection(),
kind.descriptor(),
&scope.clone().detailed(deep),
)
.await?;
let mut data = json!({ "rows": rows });
if advice_wanted(args, target) {
let keys = query::read(session.connection(), Kind::ForeignKey.descriptor(), &scope).await?;
let indexes = query::read(session.connection(), Kind::Index.descriptor(), &scope).await?;
data["advice"] = advice::for_kind(kind, &keys, &indexes);
}
annotate(session, &mut data, declared).await?;
Ok(Envelope::new(name, data))
}
pub(super) async fn views(
name: &'static str,
args: &ViewsArgs,
session: &mut Session,
target: &Target,
) -> Result<Envelope> {
let (scope, declared) = locate(session, target.database.clone(), None).await?;
if args.materialized {
let mut data = json!({ "rows": [] });
annotate(session, &mut data, declared).await?;
return Ok(Envelope::new(name, data).with_gap(Gap::new(
"materialized_view",
"unsupported",
"this server family keeps no view with a written-down result",
)));
}
let rows = query::read(
session.connection(),
Kind::View.descriptor(),
&scope.detailed(Detail::or_default(args.detail, Detail::Summary)),
)
.await?;
let mut data = json!({ "rows": rows });
annotate(session, &mut data, declared).await?;
Ok(Envelope::new(name, data))
}
pub(super) async fn events(
name: &'static str,
args: &ScopeArgs,
session: &mut Session,
target: &Target,
) -> Result<Envelope> {
let mut envelope = in_database(name, Kind::Event, args, session, target).await?;
let scheduler = query::setting(session.connection(), "SELECT @@event_scheduler").await?;
envelope.data["scheduler"] = scheduler.unwrap_or(Value::Null);
Ok(envelope)
}
pub(super) async fn sequences(
name: &'static str,
args: &ScopeArgs,
session: &mut Session,
target: &Target,
) -> Result<Envelope> {
if !session.facts().capabilities.sequences {
return Ok(
Envelope::new(name, json!({ "rows": [] })).with_gap(Gap::new(
"sequence",
"unsupported",
"this server release keeps no number generators",
)),
);
}
let mut envelope = in_database(name, Kind::Sequence, args, session, target).await?;
envelope.data["current_value_read"] = json!(false);
Ok(envelope.with_gap(Gap::new(
"sequence_current_value",
"would_change_the_server",
"reading the current value of a generator moves it on, so it is not read",
)))
}
pub(super) async fn stats(
name: &'static str,
args: &DetailedTableArgs,
session: &mut Session,
target: &Target,
) -> Result<Envelope> {
let deep = Detail::or_default(args.detail, Detail::Full);
let mut envelope = on_table(name, Kind::Statistic, args, deep, session, target).await?;
envelope.data["estimated"] = json!(true);
envelope.data["exact"] = json!(false);
Ok(envelope)
}
pub(super) async fn find(
name: &'static str,
args: &SearchArgs,
session: &mut Session,
target: &Target,
) -> Result<Envelope> {
let pattern = pattern_of(args)?;
if pattern.trim().is_empty() {
return Err(
Failure::validation("schema.empty_pattern", "the search pattern is empty")
.with_hint("give a pattern, using % where any text may stand"),
);
}
let kinds = crate::introspect::searched_kinds(&args.kind)?;
let database = target.database.clone();
let (scope, declared) = locate(session, database, None).await?;
let (rows, gaps) = crate::introspect::search(
session.connection(),
&pattern,
scope.database.as_deref(),
&kinds,
target.ceilings.search_rows,
Detail::or_default(args.detail, Detail::Summary),
)
.await?;
let mut data = json!({ "rows": rows });
annotate(session, &mut data, declared).await?;
Ok(gaps
.into_iter()
.fold(Envelope::new(name, data), Envelope::with_gap))
}
pub(super) async fn definition(
name: &'static str,
args: &DdlArgs,
session: &mut Session,
target: &Target,
) -> Result<Envelope> {
let object = object_of(args)?;
let split = names::split(&object);
let object = split.name.clone();
let database = split.database_or(target.database.clone()).ok_or_else(|| {
Failure::usage(
"schema.no_database",
"no database was named and none is in force",
)
.with_hint("name one with --database")
})?;
let found = names::resolve_database(session.connection(), &database).await?;
let kind = match args.kind.as_deref() {
Some(asked) => DefinitionKind::parse(asked).ok_or_else(|| unknown_kind(asked))?,
None => crate::introspect::kind_of(session.connection(), &found.actual, &object).await?,
};
let written =
crate::introspect::definition(session.connection(), kind, &found.actual, &object).await?;
Ok(Envelope::new(name, written))
}
pub(super) async fn count(
name: &'static str,
args: &TableArgs,
session: &mut Session,
target: &Target,
) -> Result<Envelope> {
let table = table_of(args.table.as_ref())?;
let database = target.database.clone();
let (scope, declared) = locate(session, database, Some(table)).await?;
let (Some(database), Some(table)) = (scope.database.clone(), scope.table.clone()) else {
return Err(Failure::usage(
"schema.no_database",
"no database was named and none is in force",
)
.with_hint("name one with --database"));
};
let mut data = crate::introspect::exact_count(
session.connection(),
&database,
&table,
target.ceilings.countable_rows,
)
.await?;
annotate(session, &mut data, declared).await?;
Ok(Envelope::new(name, data))
}
pub(super) async fn size(
name: &'static str,
args: &SizeArgs,
session: &mut Session,
target: &Target,
) -> Result<Envelope> {
let (scope, declared) = locate(session, target.database.clone(), None).await?;
let ranked = args.top.unwrap_or(target.ceilings.ranked_objects);
let databases = query::read(
session.connection(),
Kind::DatabaseSpace.descriptor(),
&scope,
)
.await?;
let objects = query::read(
session.connection(),
Kind::ObjectSpace.descriptor(),
&scope.clone().limited(Some(ranked)),
)
.await?;
let mut data = json!({ "rows": databases, "largest_objects": objects, "ranked": ranked });
annotate(session, &mut data, declared).await?;
let envelope = Envelope::new(name, data);
Ok(match crate::introspect::missing_space(&databases) {
Some(gap) => envelope.with_gap(gap),
None => envelope,
})
}
pub(super) async fn compact_map(
name: &'static str,
args: &MapArgs,
session: &mut Session,
target: &Target,
) -> Result<Envelope> {
let (scope, declared) = locate(session, target.database.clone(), None).await?;
let (mut data, gaps) = map::compact(
session.connection(),
scope.database.as_deref(),
args.with_comments,
target.ceilings.map,
)
.await?;
annotate(session, &mut data, declared).await?;
Ok(gaps
.into_iter()
.fold(Envelope::new(name, data), Envelope::with_gap))
}