Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions crates/cli/src/subcommands/repl.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::api::{ClientApi, Connection};
use crate::sql::run_sql;
use crate::sql::{run_sql, Format};
use colored::*;
use dirs::home_dir;
use std::env::temp_dir;
Expand Down Expand Up @@ -38,7 +38,7 @@ sort by
.clear
";

pub async fn exec(con: Connection) -> Result<(), anyhow::Error> {
pub(crate) async fn exec(con: Connection, format: Format) -> Result<(), anyhow::Error> {
let database = con.database.clone();
let mut rl = Editor::<ReplHelper, DefaultHistory>::new().unwrap();
let history = home_dir().unwrap_or_else(temp_dir).join(".stdb.history.txt");
Expand Down Expand Up @@ -71,7 +71,7 @@ pub async fn exec(con: Connection) -> Result<(), anyhow::Error> {
sql => {
rl.add_history_entry(sql).ok();

if let Err(err) = run_sql(api.sql(), sql, true).await {
if let Err(err) = run_sql(api.sql(), sql, true, format).await {
eprintln!("{}", err.to_string().red())
}
}
Expand Down
44 changes: 41 additions & 3 deletions crates/cli/src/subcommands/sql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,14 @@ pub fn cli() -> clap::Command {
.arg(common_args::confirmed())
.arg(common_args::anonymous())
.arg(common_args::server().help("The nickname, host name or URL of the server hosting the database"))
.arg(
Arg::new("format")
.long("format")
.default_value("text")
.required(false)
.value_parser(clap::value_parser!(Format))
.help("Output format for the SQL results"),
)
.arg(common_args::yes())
.arg(
Arg::new("no_config")
Expand All @@ -42,6 +50,25 @@ pub fn cli() -> clap::Command {
)
}

#[derive(Clone, Copy, PartialEq)]
pub(crate) enum Format {
Text,
Json,
}

impl clap::ValueEnum for Format {
fn value_variants<'a>() -> &'a [Self] {
&[Self::Text, Self::Json]
}

fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> {
match self {
Self::Text => Some(clap::builder::PossibleValue::new("text").aliases(["default", "txt"])),
Self::Json => Some(clap::builder::PossibleValue::new("json")),
}
}
}

pub(crate) async fn parse_req(
mut config: Config,
args: &ArgMatches,
Expand Down Expand Up @@ -143,7 +170,12 @@ fn print_stmt_result(
Ok(())
}

pub(crate) async fn run_sql(builder: RequestBuilder, sql: &str, with_stats: bool) -> Result<(), anyhow::Error> {
pub(crate) async fn run_sql(
builder: RequestBuilder,
sql: &str,
with_stats: bool,
format: Format,
) -> Result<(), anyhow::Error> {
let now = Instant::now();

let json = builder
Expand All @@ -155,6 +187,11 @@ pub(crate) async fn run_sql(builder: RequestBuilder, sql: &str, with_stats: bool
.text()
.await?;

if format == Format::Json {
println!("{json}");
return Ok(());
}

let stmt_result_json: Vec<SqlStmtResult> = serde_json::from_str(&json).context("malformed sql response")?;

let mut out = String::new();
Expand Down Expand Up @@ -182,6 +219,7 @@ pub async fn exec(config: Config, args: &ArgMatches) -> Result<(), anyhow::Error
eprintln!("{UNSTABLE_WARNING}\n");
let interactive = args.get_one::<bool>("interactive").unwrap_or(&false);
let no_config = args.get_flag("no_config");
let format = *args.get_one::<Format>("format").unwrap();
let raw_parts: Vec<String> = args
.get_many::<String>("sql_parts")
.map(|vals| vals.cloned().collect())
Expand All @@ -201,7 +239,7 @@ pub async fn exec(config: Config, args: &ArgMatches) -> Result<(), anyhow::Error
)?;
let con = parse_req(config, args, &resolved.database, resolved.server.as_deref()).await?;

crate::repl::exec(con).await?;
crate::repl::exec(con, format).await?;
} else {
let resolved = resolve_optional_database_parts(
&raw_parts,
Expand Down Expand Up @@ -243,7 +281,7 @@ pub async fn exec(config: Config, args: &ArgMatches) -> Result<(), anyhow::Error
api = api.query(&[("confirmed", if confirmed { "true" } else { "false" })]);
}

run_sql(api, &query, false).await?;
run_sql(api, &query, false, format).await?;
}
Ok(())
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,12 @@ Runs a SQL query on the database. WARNING: This command is UNSTABLE and subject

* `--anonymous` — Perform this action with an anonymous identity
* `-s`, `--server <SERVER>` — The nickname, host name or URL of the server hosting the database
* `--format <FORMAT>` — Output format for the SQL results

Default value: `text`

Possible values: `text`, `json`

* `-y`, `--yes` — Run non-interactively wherever possible. This will answer "yes" to almost all prompts, but will sometimes answer "no" to preserve non-interactivity (e.g. when prompting whether to log in with spacetimedb.com).
* `--no-config` — Ignore spacetime.json configuration

Expand Down
Loading