-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathcli.rs
More file actions
397 lines (341 loc) · 11 KB
/
Copy pathcli.rs
File metadata and controls
397 lines (341 loc) · 11 KB
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/*!
ggsql Command Line Interface
Provides commands for executing ggsql queries with various data sources and output formats.
*/
use clap::{Parser, Subcommand};
use ggsql::{parser, VERSION};
use std::path::PathBuf;
#[cfg(feature = "duckdb")]
use ggsql::reader::{DuckDBReader, Reader};
#[cfg(feature = "duckdb")]
use ggsql::validate::validate;
#[cfg(feature = "vegalite")]
use ggsql::writer::{VegaLiteWriter, Writer};
#[derive(Parser)]
#[command(name = "ggsql")]
#[command(about = "SQL extension for declarative data visualization")]
#[command(version = VERSION)]
pub struct Cli {
#[command(subcommand)]
pub command: Commands,
}
#[derive(Subcommand)]
pub enum Commands {
/// Execute a ggsql query
Exec {
/// The ggsql query to execute
query: String,
/// Data source connection string
#[arg(long, default_value = "duckdb://memory")]
reader: String,
/// Output format
#[arg(long, default_value = "vegalite")]
writer: String,
/// Output file path
#[arg(long)]
output: Option<PathBuf>,
/// Show verbose output (execution details, statistics)
#[arg(short, long)]
verbose: bool,
},
/// Execute a ggsql query from a file
Run {
/// Path to .sql file containing ggsql query
file: PathBuf,
/// Data source connection string
#[arg(long, default_value = "duckdb://memory")]
reader: String,
/// Output format
#[arg(long, default_value = "vegalite")]
writer: String,
/// Output file path
#[arg(long)]
output: Option<PathBuf>,
/// Show verbose output (execution details, statistics)
#[arg(short, long)]
verbose: bool,
},
/// Parse a query and show the AST (for debugging)
Parse {
/// The ggsql query to parse
query: String,
/// Output format for AST (json, debug, pretty)
#[arg(long, default_value = "pretty")]
format: String,
},
/// Validate a query without executing
Validate {
/// The ggsql query to validate
query: String,
/// Data source connection string (needed for column validation)
#[arg(long)]
reader: Option<String>,
},
}
fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
match cli.command {
Commands::Exec {
query,
reader,
writer,
output,
verbose,
} => {
if verbose {
eprintln!("Executing query: {}", query);
}
cmd_exec(query, reader, writer, output, verbose);
}
Commands::Run {
file,
reader,
writer,
output,
verbose,
} => {
if verbose {
eprintln!("Running query from file: {}", file.display());
}
cmd_run(file, reader, writer, output, verbose);
}
Commands::Parse { query, format } => {
cmd_parse(query, format);
}
Commands::Validate { query, reader } => {
cmd_validate(query, reader);
}
}
Ok(())
}
fn cmd_run(file: PathBuf, reader: String, writer: String, output: Option<PathBuf>, verbose: bool) {
match std::fs::read_to_string(&file) {
Ok(query) => cmd_exec(query, reader, writer, output, verbose),
Err(e) => {
eprintln!("Failed to read file {}: {}", file.display(), e);
std::process::exit(1);
}
}
}
fn cmd_exec(query: String, reader: String, writer: String, output: Option<PathBuf>, verbose: bool) {
if verbose {
eprintln!("Reader: {}", reader);
eprintln!("Writer: {}", writer);
if let Some(ref output_file) = output {
eprintln!("Output: {}", output_file.display());
}
}
// Setup reader
#[cfg(feature = "duckdb")]
if !reader.starts_with("duckdb://") {
eprintln!("Unsupported reader: {}", reader);
eprintln!("Currently only 'duckdb://' readers are supported");
std::process::exit(1);
}
let db_reader = DuckDBReader::from_connection_string(&reader);
if let Err(e) = db_reader {
eprintln!("Failed to create DuckDB reader: {}", e);
std::process::exit(1);
}
let db_reader = db_reader.unwrap();
// Use validate() to check if query has visualization
let validated = match validate(&query) {
Ok(v) => v,
Err(e) => {
eprintln!("Failed to validate query: {}", e);
std::process::exit(1);
}
};
if !validated.has_visual() {
if verbose {
eprintln!("Visualisation is empty. Printing table instead.");
}
print_table_fallback(&query, &db_reader, 100);
return;
}
// Execute ggsql query
let spec = match db_reader.execute(&query) {
Ok(s) => s,
Err(e) => {
eprintln!("Failed to execute query: {}", e);
std::process::exit(1);
}
};
if verbose {
let metadata = spec.metadata();
eprintln!("\nQuery executed:");
eprintln!(" Rows: {}", metadata.rows);
eprintln!(" Columns: {}", metadata.columns.join(", "));
eprintln!(" Layers: {}", metadata.layer_count);
}
if spec.plot().layers.is_empty() {
eprintln!("No visualization specifications found");
std::process::exit(1);
}
// Check writer
if writer != "vegalite" {
eprintln!("\nNote: Writer '{}' not yet implemented", writer);
eprintln!("Available writers: vegalite")
}
#[cfg(not(feature = "vegalite"))]
{
eprintln!("VegaLite writer not compiled in. Rebuild with --features vegalite");
std::process::exit(1)
}
// Render
let vl_writer = VegaLiteWriter::new();
let json_output = match vl_writer.render(&spec) {
Ok(r) => r,
Err(e) => {
eprintln!("Failed to generate Vega-Lite output: {}", e);
std::process::exit(1);
}
};
if output.is_none() {
// Empty output location, write to stdout
println!("{}", json_output);
return;
}
let output = output.unwrap();
// Write to file
match std::fs::write(&output, json_output) {
Ok(_) => {
if verbose {
eprintln!("\nVega-Lite JSON written to: {}", output.display());
}
}
Err(e) => {
eprintln!("Failed to write to output file: {}", e);
std::process::exit(1);
}
}
}
fn cmd_parse(query: String, format: String) {
println!("Parsing query: {}", query);
println!("Format: {}", format);
let parsed = parser::parse_query(&query);
if let Err(e) = parsed {
eprintln!("Parse error: {}", e);
std::process::exit(1);
}
// TODO: implement parsing logic
let specs = parsed.unwrap();
match format.as_str() {
"json" => match serde_json::to_string_pretty(&specs) {
Ok(pretty) => println!("{}", pretty),
Err(error) => eprintln!("{}", error),
},
"debug" => println!("{:#?}", specs),
"pretty" => {
println!("ggsql Specifications: {} total", specs.len());
for (i, spec) in specs.iter().enumerate() {
println!("\nVisualization #{}:", i + 1);
println!(" Global Mappings: {:?}", spec.global_mappings);
println!(" Layers: {}", spec.layers.len());
println!(" Scales: {}", spec.scales.len());
if spec.facet.is_some() {
println!(" Faceting: Yes");
}
if spec.theme.is_some() {
println!(" Theme: Yes");
}
}
}
_ => {
eprintln!("Unknown format: {}", format);
std::process::exit(1);
}
}
}
fn cmd_validate(query: String, _reader: Option<String>) {
#[cfg(feature = "duckdb")]
{
match validate(&query) {
Ok(validated) if validated.valid() => {
println!("✓ Query syntax is valid");
}
Ok(validated) => {
println!("✗ Validation errors:");
for err in validated.errors() {
println!(" - {}", err.message);
}
if !validated.warnings().is_empty() {
println!("\nWarnings:");
for warning in validated.warnings() {
println!(" - {}", warning.message);
}
}
std::process::exit(1);
}
Err(e) => {
eprintln!("Error during validation: {}", e);
std::process::exit(1);
}
}
}
#[cfg(not(feature = "duckdb"))]
{
eprintln!("Validation requires the duckdb feature");
std::process::exit(1);
}
}
// Prints a CSV-like output to stdout with aligned columns
fn print_table_fallback(query: &str, reader: &DuckDBReader, max_rows: usize) {
let source_tree = match parser::SourceTree::new(query) {
Ok(st) => st,
Err(e) => {
eprintln!("Failed to parse query: {}", e);
std::process::exit(1);
}
};
let sql_part = match source_tree.extract_sql() {
Ok(sql) => sql.unwrap_or_default(),
Err(e) => {
eprintln!("SQL validation error: {}", e);
std::process::exit(1);
}
};
let data = reader.execute_sql(&sql_part);
if let Err(e) = data {
eprintln!("Failed to execute SQL query: {}", e);
std::process::exit(1)
}
let data = data.unwrap();
let nrow = data.height().min(max_rows);
let ncol = data.width();
let colnames = data.get_column_names_str();
// We add an extra 'row' for the column names
let mut rows: Vec<String> = vec![String::from(""); nrow + 1];
for col_id in 0..ncol {
let col_name = colnames[col_id];
let mut width = col_name.chars().count();
// End last column without comma
let mut suffix = ", ";
if col_id == ncol - 1 {
suffix = "";
}
// Prepopulate formatted column with column name
let mut col_fmt: Vec<String> = vec![format!("{}{}", col_name, suffix)];
// Format every cell in column, tracking width
let column_data = data[col_id].as_materialized_series();
for cell in column_data.iter().take(rows.len()) {
let cell_fmt = format!("{}{}", cell, suffix);
let nchar = cell_fmt.chars().count();
if nchar > width {
width = nchar;
}
col_fmt.push(cell_fmt);
}
// Pad strings with spaces
let col_fmt: Vec<String> = col_fmt
.into_iter()
.map(|s| format!("{:width$}", s, width = width))
.collect();
// Push columns to row string
for i in 0..rows.len() {
rows[i].push_str(col_fmt[i].as_str());
}
}
let output = rows.join("\n");
println!("{}", output);
}