use super::{
AggregateArgs, CallKind, Command, FIXTURE_OUTPUT_BYTES, FixtureCalls, QueryArgs, help,
print_schema, print_schema_json, print_status,
};
use ic_db_cli::{
ConsolePage, DisplayPage, QueryOptions, QueryRequest, RetainedPhase, RetainedProgress,
RetainedSelection, lowercase_hex,
};
use ic_host_text::{bordered_table, escape};
async fn count(calls: &mut FixtureCalls<'_>, entity: &str) -> Result<(), String> {
let count: Result<u64, String> = calls
.framed(CallKind::Query, "cardinality", 148, entity)
.await?;
println!(
"{}",
bordered_table(&["count"], &[vec![count?.to_string()]])
);
Ok(())
}
async fn schema(
calls: &mut FixtureCalls<'_>,
selected: Option<String>,
json: bool,
) -> Result<(), String> {
let ic_db_cli::SchemaResponse {
status,
entities,
types,
} = fetch_schema(calls, &selected).await?;
if entities.is_empty()
&& let Some(name) = selected
{
return Err(format!(
"Unknown entity '{}'. Use db entities to list entities.",
escape(&name)
));
}
if json {
print_schema_json(status.schema, &entities, &types)?;
} else {
print_schema(entities, types);
}
Ok(())
}
async fn fetch_schema(
calls: &mut FixtureCalls<'_>,
selected: &Option<String>,
) -> Result<ic_db_cli::SchemaResponse, String> {
calls.framed(CallKind::Query, "schema", 2, selected).await
}
async fn entities(calls: &mut FixtureCalls<'_>, json: bool) -> Result<(), String> {
let entities = fetch_schema(calls, &None).await?.entities;
#[derive(serde::Serialize)]
struct Summary {
name: String,
columns: usize,
}
let mut summaries: Vec<_> = entities
.into_iter()
.map(|entity| Summary {
name: entity.name,
columns: entity.fields.len(),
})
.collect();
summaries.sort_by(|a, b| a.name.cmp(&b.name));
if json {
println!(
"{}",
serde_json::to_string_pretty(&summaries).map_err(|e| e.to_string())?
);
} else {
let rows: Vec<_> = summaries
.into_iter()
.map(|s| vec![s.name, s.columns.to_string()])
.collect();
println!("{}", bordered_table(&["Entity", "Columns"], &rows));
}
Ok(())
}
async fn migration(calls: &mut FixtureCalls<'_>, wasm: &[u8]) -> Result<(), String> {
let pic = calls.pic;
let canister = calls.canister;
use ic_db_cli::MigrationAction;
let mut step = async |action: MigrationAction| -> Result<(bool, Vec<Vec<String>>), String> {
calls
.framed(CallKind::Update, "migration_demo", 142, &action)
.await?
};
let (_, rows) = step(MigrationAction::Seed).await?;
println!(
"\nItem — source\n{}",
bordered_table(&["id", "amount"], &rows)
);
println!("\nMigration: console-item-label v1");
for action in [
MigrationAction::Freeze,
MigrationAction::Copy,
MigrationAction::Validate,
MigrationAction::Publish,
MigrationAction::Cleanup,
] {
for call in 1..=32 {
let (complete, rows) = step(action).await?;
println!(
"{action:?} {call}: {}",
if complete { "complete" } else { "in progress" }
);
if action == MigrationAction::Copy {
println!("{}", bordered_table(&["Copied rows"], &rows));
if call == 1 {
ic_db_cli::host::upgrade_stopped(pic, canister, wasm.to_vec(), vec![], None)
.await
.map_err(|e| format!("{e:?}"))?;
println!("Upgrade: complete");
}
}
if complete {
break;
}
if call == 32 {
return Err(format!("{action:?} exceeded the fixture's 32-call bound"));
}
}
}
let (_, rows) = step(MigrationAction::ReadTarget).await?;
println!(
"\nItem — target (label index)\n{}",
bordered_table(&["id", "amount", "label"], &rows)
);
Ok(())
}
pub(super) async fn execute(
calls: &mut FixtureCalls<'_>,
command: Command,
wasm: &[u8],
) -> Result<(), String> {
match command {
Command::Help => help(),
Command::Quit => {}
Command::MigrationDemo => migration(calls, wasm).await?,
Command::Aggregate(args) => aggregate(calls, args).await?,
Command::Count { entity } => count(calls, &entity).await?,
Command::Schema { entity, json } => schema(calls, entity, json).await?,
Command::Entities { json } => entities(calls, json).await?,
Command::Status => print_status(calls.framed(CallKind::Query, "inspect", 1, &()).await?),
Command::Query(args) => query(calls, args).await?,
}
Ok(())
}
async fn query(calls: &mut FixtureCalls<'_>, args: QueryArgs) -> Result<(), String> {
let request = QueryRequest {
entity: args.entity,
cursor: args.after.map(|cursor| cursor.to_bytes()),
limit: args.limit,
entity_filters: args.entity_filters,
order: args.order.order_by,
descending: args.order.desc,
work: args.work,
bytes: FIXTURE_OUTPUT_BYTES,
select: args.select,
options: QueryOptions {
distinct: args.distinct,
group_bounds: args.group_bounds,
group_order: args.group_order,
filters: args.filters.into_filters()?,
},
};
let result: Result<ConsolePage, String> =
calls.framed(CallKind::Query, "query", 3, &request).await?;
let ConsolePage {
page: DisplayPage {
columns,
rows,
next,
},
examined,
fetched,
output_bytes: bytes,
} = result?;
let count = rows.len();
println!("\n{}\n{}", request.entity, bordered_table(&columns, &rows));
let noun = if count == 1 { "row" } else { "rows" };
println!("{count} {noun}; {examined} examined; {fetched} fetched; {bytes} encoded bytes.");
println!(
"Next cursor: {}",
next.map_or_else(|| "none".into(), |c| lowercase_hex(&c, ""))
);
Ok(())
}
async fn aggregate(calls: &mut FixtureCalls<'_>, args: AggregateArgs) -> Result<(), String> {
let selection = RetainedSelection {
entity: args.entity,
select: args.select,
entity_filters: args.entity_filters,
limit: args.limit,
group_bounds: args.group_bounds,
group_order: args.group_order,
filters: args.filters.into_filters()?,
order: (args.order.order_by, args.order.desc),
};
let handle = calls
.framed::<Result<Vec<u8>, String>>(CallKind::Update, "aggregate_start", 120, &selection)
.await??;
println!("\n{} — {}", selection.entity, selection.select);
let mut request = ic_db_cli::RetainedResume {
selection,
handle,
sequence: 0,
work: args.work,
bytes: FIXTURE_OUTPUT_BYTES,
page_size: args.page_size,
after: None,
};
let run = resume(calls, &mut request).await;
let cleanup = calls
.framed::<Result<(), String>>(CallKind::Update, "aggregate_cancel", 122, &request.handle)
.await
.and_then(|result| result);
match (run, cleanup) {
(Ok(()), result) | (result, Ok(())) => result,
(Err(error), Err(cleanup)) => Err(format!("{error}; cleanup: {cleanup}")),
}
}
async fn resume(
calls: &mut FixtureCalls<'_>,
request: &mut ic_db_cli::RetainedResume,
) -> Result<(), String> {
for call in 1..=32 {
let result: Result<RetainedProgress, String> = calls
.framed(CallKind::Update, "aggregate_resume", 121, request)
.await?;
let RetainedProgress {
sequence: saved,
phase,
examined,
input_bytes,
output_bytes,
} = result?;
let label = phase.label();
println!(
"Call {call}: {label}; sequence {saved}; {examined} examined; {input_bytes} input bytes; {output_bytes} output bytes."
);
request.sequence = saved;
match phase {
RetainedPhase::Running => {}
RetainedPhase::Complete(DisplayPage {
columns,
rows,
next,
}) => {
println!("{}", bordered_table(&columns, &rows));
if next.is_none() {
return Ok(());
}
request.after = next;
}
RetainedPhase::Expired | RetainedPhase::Invalidated => {
return Err(format!("aggregate {label}"));
}
}
}
Err("aggregate exceeded the fixture's 32-call bound".into())
}