diff --git a/CLAUDE.md b/CLAUDE.md index ee82ced..1a9e81f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -19,7 +19,7 @@ When in doubt, ask before committing. The cost of pausing is low; the cost of a ## What this crate is -A Rust CLI that wraps the `quicknode-sdk` crate (v0.9). The SDK has four sub-clients (`admin`, `streams`, `webhooks`, `kvstore`); `qn` exposes every public method on each as a noun-verb subcommand. CLI behavior follows the [Command Line Interface Guidelines](https://clig.dev). +A Rust CLI that wraps the `quicknode-sdk` crate (v0.10). The SDK has four sub-clients (`admin`, `streams`, `webhooks`, `kvstore`); `qn` exposes every public method on each as a noun-verb subcommand. CLI behavior follows the [Command Line Interface Guidelines](https://clig.dev). ## Architecture diff --git a/Cargo.lock b/Cargo.lock index e96c7c3..0bfd203 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3245,9 +3245,9 @@ dependencies = [ [[package]] name = "quicknode-sdk" -version = "0.9.0" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb9696a8b44e88b30c8550836ad6d924e3b8ae8a88a453731a4dacc8fd1a5257" +checksum = "87fd8a9e908eb776339040a89268c44e2e6f8ccf895fa79bec0e4d74a787e682" dependencies = [ "alloy-consensus", "alloy-primitives", diff --git a/Cargo.toml b/Cargo.toml index 04cb80f..f9c1a3e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ name = "qn" path = "src/lib.rs" [dependencies] -quicknode-sdk = { version = "0.9.0", features = [ +quicknode-sdk = { version = "0.10.1", features = [ "payments", # x402/EVM "payments-svm", # + x402/Solana "payments-tempo", # + MPP/Tempo diff --git a/README.md b/README.md index 78fef53..875406c 100644 --- a/README.md +++ b/README.md @@ -274,6 +274,9 @@ qn kv list get allowlist ### SQL ```sh +# List the clusters you can query +qn sql clusters + # Run a query inline, from a file, or from stdin (--file -) qn sql query "SELECT action_type, user FROM hyperliquid_system_actions ORDER BY block_time DESC LIMIT 3" --cluster-id hyperliquid-core-mainnet qn sql query --file query.sql --cluster-id hyperliquid-core-mainnet diff --git a/src/cli.rs b/src/cli.rs index 13a373f..8376ce2 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -160,7 +160,7 @@ pub enum Command { /// Manage the Quicknode KV store (sets and lists). Kv(commands::kv::Args), - /// Run SQL queries and inspect cluster schemas. + /// List clusters, run SQL queries, and inspect cluster schemas. Sql(commands::sql::Args), /// Make RPC calls. diff --git a/src/commands/agent/context.md b/src/commands/agent/context.md index 5fb7456..d75c581 100644 --- a/src/commands/agent/context.md +++ b/src/commands/agent/context.md @@ -108,7 +108,8 @@ if you need it. - `qn stream test-filter` evaluates a filter against historical data and changes nothing — it is read-only and safe to retry. - `qn sql query` is read-only but **does not auto-retry**: a query consumes credits, - so a retried query re-bills. `qn sql schema` is a cheap read and retries normally. + so a retried query re-bills. `qn sql clusters` and `qn sql schema` are cheap + reads and retry normally. - A **paid** `rpc call` (`--x402`/`--mpp`/`--x402-drawdown`/`--mpp-session`) never auto-retries — `--retries` does not apply. A per-request attempt can move funds, and after a lost response the previous attempt may already have @@ -151,7 +152,8 @@ Top-level nouns (plurals like `endpoints`/`streams` and `ls` are accepted aliase enabled-count - `kv` — `set` (put, get, list, delete, bulk) and `list` (list, get, create, append, contains, remove-item, update, delete) -- `sql` — query (inline SQL, `--file `, or `--file -` for stdin), schema +- `sql` — clusters (alias `ls`; lists the cluster ids `query` and `schema` take), + query (inline SQL, `--file `, or `--file -` for stdin), schema - `tooling-access` — status, enable, disable (provisions the endpoint `rpc` uses) - `rpc` — make JSON-RPC calls. `qn rpc call [json-params]` calls the account's Tooling Access endpoint (params is a JSON array or object inline, or diff --git a/src/commands/sql/mod.rs b/src/commands/sql/mod.rs index 0e63010..3bc893e 100644 --- a/src/commands/sql/mod.rs +++ b/src/commands/sql/mod.rs @@ -1,4 +1,4 @@ -//! `qn sql …` — run SQL queries and inspect cluster schemas. +//! `qn sql …` — list clusters, run SQL queries, and inspect cluster schemas. mod render; @@ -7,7 +7,7 @@ use std::path::PathBuf; use clap::{ArgGroup, Args as ClapArgs, Subcommand}; use comfy_table::Cell; -use quicknode_sdk::{ChainSchema, QueryParams, QueryResponse}; +use quicknode_sdk::{ChainSchema, QueryParams, QueryResponse, SqlCluster}; use serde::Serialize; use serde_json::Value; @@ -18,6 +18,10 @@ use crate::retry::retrying; use render::json_cell; #[derive(Debug, ClapArgs)] +#[command(after_help = "Examples:\n \ + qn sql clusters\n \ + qn sql schema hyperliquid-core-mainnet\n \ + qn sql query \"SELECT 1\" --cluster-id hyperliquid-core-mainnet")] pub struct Args { #[command(subcommand)] pub cmd: SqlCmd, @@ -25,6 +29,10 @@ pub struct Args { #[derive(Debug, Subcommand)] pub enum SqlCmd { + /// List the clusters you can query. + #[command(visible_alias = "ls")] + Clusters, + /// Run a read-only SQL query against a cluster. /// /// The query may be passed inline, read from a file with --file, or read @@ -65,11 +73,17 @@ pub struct SchemaArgs { pub async fn run(args: Args, ctx: Ctx) -> Result<(), CliError> { match args.cmd { + SqlCmd::Clusters => clusters(ctx).await, SqlCmd::Query(a) => query(a, ctx).await, SqlCmd::Schema(a) => schema(a, ctx).await, } } +async fn clusters(ctx: Ctx) -> Result<(), CliError> { + let resp = retrying(ctx.global.retries, || ctx.sdk.sql.list_clusters()).await?; + crate::output::emit(&ctx.out, &ClustersView(resp)) +} + async fn query(a: QueryArgs, ctx: Ctx) -> Result<(), CliError> { let sql = resolve_query(a.query, a.file)?; let params = QueryParams { @@ -118,12 +132,14 @@ fn resolve_query(query: Option, file: Option) -> Result String { - let mut line = format!( - "✓ {} rows · {} credits · {:.3}s", - resp.rows, resp.credits, resp.statistics.elapsed - ); + let mut line = format!("✓ {} rows", resp.rows); + if let Some(credits) = resp.credits { + line.push_str(&format!(" · {credits} credits")); + } + line.push_str(&format!(" · {:.3}s", resp.statistics.elapsed)); if resp.rows_before_limit_at_least > resp.rows { line.push_str(&format!( " · {} matched (use LIMIT/OFFSET to page)", @@ -133,6 +149,27 @@ fn stats_line(resp: &QueryResponse) -> String { line } +#[derive(Serialize)] +struct ClustersView(Vec); + +impl Render for ClustersView { + fn render_table( + &self, + w: &mut dyn std::io::Write, + ctx: &crate::output::OutputCtx, + ) -> std::io::Result<()> { + let mut t = new_table(ctx); + set_header_bold(&mut t, ctx, vec!["ID", "DISPLAY_NAME"]); + for cluster in &self.0 { + t.add_row(vec![ + Cell::new(&cluster.id), + Cell::new(&cluster.display_name), + ]); + } + write_table(w, &t) + } +} + #[derive(Serialize)] struct QueryView(QueryResponse); @@ -209,3 +246,36 @@ impl Render for SchemaView { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn response(credits: Option) -> QueryResponse { + let mut body = json!({ + "meta": [], + "data": [], + "rows": 2, + "rows_before_limit_at_least": 2, + "statistics": {"elapsed": 0.0067, "rows_read": 10, "bytes_read": 100} + }); + if let Some(c) = credits { + body["credits"] = json!(c); + } + serde_json::from_value(body).unwrap() + } + + #[test] + fn stats_line_includes_credits_when_present() { + assert_eq!( + stats_line(&response(Some(135))), + "✓ 2 rows · 135 credits · 0.007s" + ); + } + + #[test] + fn stats_line_omits_credits_when_absent() { + assert_eq!(stats_line(&response(None)), "✓ 2 rows · 0.007s"); + } +} diff --git a/tests/snapshots/table_snapshots__sql_clusters_table_renders_id_and_display_name.snap b/tests/snapshots/table_snapshots__sql_clusters_table_renders_id_and_display_name.snap new file mode 100644 index 0000000..b766ccf --- /dev/null +++ b/tests/snapshots/table_snapshots__sql_clusters_table_renders_id_and_display_name.snap @@ -0,0 +1,7 @@ +--- +source: tests/table_snapshots.rs +expression: out +--- +ID DISPLAY_NAME +hyperliquid-core-mainnet Hyperliquid (HyperCore) +solana-mainnet Solana diff --git a/tests/sql.rs b/tests/sql.rs index 4d31260..f849159 100644 --- a/tests/sql.rs +++ b/tests/sql.rs @@ -5,7 +5,7 @@ mod common; use common::run_qn; use serde_json::json; use std::io::Write; -use wiremock::matchers::{body_partial_json, method, path}; +use wiremock::matchers::{body_partial_json, header, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; fn query_body() -> serde_json::Value { @@ -207,3 +207,52 @@ async fn schema_not_found_maps_to_exit_2() { let out = run_qn(&server.uri(), &["sql", "schema", "bad-cluster"]).await; assert_eq!(out.exit_code, 2, "stderr={}", out.stderr); } + +#[tokio::test] +async fn query_response_without_credits_succeeds() { + let server = MockServer::start().await; + let mut body = query_body(); + body.as_object_mut().unwrap().remove("credits"); + Mock::given(method("POST")) + .and(path("/sql/rest/v1/query")) + .respond_with(ResponseTemplate::new(200).set_body_json(body)) + .mount(&server) + .await; + let out = run_qn( + &server.uri(), + &["sql", "query", "SELECT 1", "--cluster-id", "c1"], + ) + .await; + assert_eq!(out.exit_code, 0, "stderr={}", out.stderr); +} + +#[tokio::test] +async fn clusters_and_ls_alias_send_the_api_key() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/sql/rest/v1/clusters")) + .and(header("x-api-key", "test")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!([ + {"id": "hyperliquid-core-mainnet", "display_name": "Hyperliquid (HyperCore)"}, + {"id": "solana-mainnet", "display_name": "Solana"} + ]))) + .expect(2) + .mount(&server) + .await; + let out = run_qn(&server.uri(), &["sql", "clusters"]).await; + assert_eq!(out.exit_code, 0, "stderr={}", out.stderr); + let out = run_qn(&server.uri(), &["sql", "ls"]).await; + assert_eq!(out.exit_code, 0, "stderr={}", out.stderr); +} + +#[tokio::test] +async fn clusters_unauthorized_maps_to_exit_2() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/sql/rest/v1/clusters")) + .respond_with(ResponseTemplate::new(401).set_body_string("Unauthorized")) + .mount(&server) + .await; + let out = run_qn(&server.uri(), &["sql", "clusters"]).await; + assert_eq!(out.exit_code, 2, "stderr={}", out.stderr); +} diff --git a/tests/table_snapshots.rs b/tests/table_snapshots.rs index ba81463..97b1fad 100644 --- a/tests/table_snapshots.rs +++ b/tests/table_snapshots.rs @@ -809,6 +809,16 @@ async fn sql_query_table_renders_unquoted_scalars_and_null_dash() { insta::assert_snapshot!(out); } +#[tokio::test] +async fn sql_clusters_table_renders_id_and_display_name() { + let body = serde_json::json!([ + {"id": "hyperliquid-core-mainnet", "display_name": "Hyperliquid (HyperCore)"}, + {"id": "solana-mainnet", "display_name": "Solana"} + ]); + let out = table_stdout("/sql/rest/v1/clusters", body, &["sql", "clusters"]).await; + insta::assert_snapshot!(out); +} + #[tokio::test] async fn sql_schema_table_renders_nested_table_blocks() { let body = serde_json::json!({