Skip to content
Open
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
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 4 additions & 2 deletions src/commands/agent/context.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 <path>`, or `--file -` for stdin), schema
- `sql` — clusters (alias `ls`; lists the cluster ids `query` and `schema` take),
query (inline SQL, `--file <path>`, or `--file -` for stdin), schema
- `tooling-access` — status, enable, disable (provisions the endpoint `rpc` uses)
- `rpc` — make JSON-RPC calls. `qn rpc call <method> [json-params]` calls the
account's Tooling Access endpoint (params is a JSON array or object inline, or
Expand Down
84 changes: 77 additions & 7 deletions src/commands/sql/mod.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -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;

Expand All @@ -18,13 +18,21 @@ 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,
}

#[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
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -118,12 +132,14 @@ fn resolve_query(query: Option<String>, file: Option<PathBuf>) -> Result<String,

/// Builds the human-facing stats note, e.g.
/// `✓ 2 rows · 135 credits · 0.007s` plus a truncation hint when the result set
/// was capped below the total matched.
/// was capped below the total matched. The credits segment is left out when
/// the response has no credits value.
fn stats_line(resp: &QueryResponse) -> 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)",
Expand All @@ -133,6 +149,27 @@ fn stats_line(resp: &QueryResponse) -> String {
line
}

#[derive(Serialize)]
struct ClustersView(Vec<SqlCluster>);

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);

Expand Down Expand Up @@ -209,3 +246,36 @@ impl Render for SchemaView {
Ok(())
}
}

#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;

fn response(credits: Option<i64>) -> 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");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
source: tests/table_snapshots.rs
expression: out
---
ID DISPLAY_NAME
hyperliquid-core-mainnet Hyperliquid (HyperCore)
solana-mainnet Solana
51 changes: 50 additions & 1 deletion tests/sql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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);
}
10 changes: 10 additions & 0 deletions tests/table_snapshots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!({
Expand Down
Loading