1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
//! `boatramp sql` — operator SQL access to a **managed** database: apply a
//! migration script (`exec`) or run a single query (`query`). The server connects
//! using the database's sealed managed credential (resolved server-side — the
//! credential never reaches the client) and runs the SQL; admin-scoped.
use clap::Subcommand;
use crate::client;
use crate::config::ProjectConfig;
/// `sql` module result; `Err` is [`Error`].
type Result<T> = std::result::Result<T, Error>;
/// A `boatramp sql` failure.
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// Resolving the server target from flags/config failed.
#[error(transparent)]
Client(#[from] crate::client::ClientError),
/// A control-plane HTTP request failed.
#[error("control-plane request: {0}")]
Http(#[from] reqwest::Error),
/// (De)serializing JSON failed.
#[error(transparent)]
Json(#[from] serde_json::Error),
/// Reading the script file / stdin failed.
#[error(transparent)]
Io(#[from] std::io::Error),
/// The control-plane returned an error response.
#[error("{0}")]
Server(String),
}
/// Arguments for `boatramp sql`.
#[derive(Debug, clap::Args)]
pub struct SqlArgs {
/// boatramp server base URL (overrides [deploy].server).
#[arg(long, env = "BOATRAMP_SERVER", global = true)]
server: Option<String>,
#[command(subcommand)]
command: SqlCommand,
}
#[derive(Debug, Subcommand)]
enum SqlCommand {
/// Apply a migration **script** (multiple statements — `CREATE EXTENSION`,
/// tables, RLS, chained DDL/DML) to a managed database. Reads from `--file` or
/// standard input.
Exec {
/// The database binding name (empty = the site's default database).
#[arg(long, default_value = "")]
db: String,
/// Read the script from this file instead of standard input.
#[arg(long)]
file: Option<std::path::PathBuf>,
},
/// Run one row-returning query against a managed database and print the result.
Query {
/// The SQL query (a single statement).
sql: String,
/// The database binding name (empty = the site's default database).
#[arg(long, default_value = "")]
db: String,
/// Output format.
#[arg(long, value_enum, default_value_t = Format::Table)]
format: Format,
},
}
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum Format {
/// A bordered text table.
Table,
/// The raw `{columns, rows}` JSON.
Json,
}
/// Entry point for `boatramp sql`.
pub async fn run(args: SqlArgs, config: &ProjectConfig) -> Result<()> {
let server = client::resolve_server(args.server, config)?;
let http = client::http_client(client::token(config).as_deref());
match args.command {
SqlCommand::Exec { db, file } => {
let sql = match file {
Some(path) => std::fs::read_to_string(path)?,
None => {
use std::io::Read;
let mut s = String::new();
std::io::stdin().read_to_string(&mut s)?;
s
}
};
let resp = http
.post(format!("{server}/api/sql/{db}/exec"))
.json(&serde_json::json!({ "sql": sql }))
.send()
.await?;
let status = resp.status();
if !status.is_success() {
let text = resp.text().await.unwrap_or_default();
return Err(Error::Server(format!(
"sql exec failed: {status}: {}",
text.trim()
)));
}
eprintln!("ok");
}
SqlCommand::Query { db, sql, format } => {
let resp = http
.post(format!("{server}/api/sql/{db}/query"))
.json(&serde_json::json!({ "sql": sql }))
.send()
.await?;
let status = resp.status();
if !status.is_success() {
let text = resp.text().await.unwrap_or_default();
return Err(Error::Server(format!(
"sql query failed: {status}: {}",
text.trim()
)));
}
let out: serde_json::Value = resp.json().await?;
match format {
Format::Json => println!("{}", serde_json::to_string_pretty(&out)?),
Format::Table => print_table(&out),
}
}
}
Ok(())
}
/// Render a `{columns, rows}` query response as a bordered text table.
fn print_table(out: &serde_json::Value) {
let headers: Vec<String> = out["columns"]
.as_array()
.map(|a| {
a.iter()
.map(|c| c.as_str().unwrap_or("").to_string())
.collect()
})
.unwrap_or_default();
let mut widths: Vec<usize> = headers.iter().map(String::len).collect();
let cells: Vec<Vec<String>> = out["rows"]
.as_array()
.map(|rows| {
rows.iter()
.map(|r| {
r.as_array()
.map(|cols| {
cols.iter()
.enumerate()
.map(|(i, v)| {
let s = match v {
serde_json::Value::String(s) => s.clone(),
serde_json::Value::Null => String::new(),
other => other.to_string(),
};
if i < widths.len() {
widths[i] = widths[i].max(s.len());
}
s
})
.collect()
})
.unwrap_or_default()
})
.collect()
})
.unwrap_or_default();
let fmt_row = |vals: &[String]| -> String {
vals.iter()
.enumerate()
.map(|(i, v)| format!("{:width$}", v, width = widths.get(i).copied().unwrap_or(0)))
.collect::<Vec<_>>()
.join(" | ")
};
println!("{}", fmt_row(&headers));
println!(
"{}",
widths
.iter()
.map(|w| "-".repeat(*w))
.collect::<Vec<_>>()
.join("-+-")
);
for row in &cells {
println!("{}", fmt_row(row));
}
println!(
"({} row{})",
cells.len(),
if cells.len() == 1 { "" } else { "s" }
);
}