ggsql 0.5.0

A declarative visualization language that extends SQL with powerful data visualization capabilities.
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# ggsql API Reference

This document provides a comprehensive reference for the ggsql public API.

## Overview

- **Stage 1: `reader.execute()`** - Parse query, execute SQL, resolve mappings, create Spec
- **Stage 2: `writer.render()`** - Generate output (Vega-Lite JSON, SVG, PDF, PNG, …)

### API Functions

| Function           | Use Case                                             |
| ------------------ | ---------------------------------------------------- |
| `reader.execute()` | Main entry point - full visualization pipeline       |
| `writer.render()`  | Generate output from Spec                            |
| `validate()`       | Validate syntax + semantics, inspect query structure |

---

## Core Functions

### `Reader::execute`

```rust
fn execute(&self, query: &str) -> Result<Spec>
```

Execute a ggsql query for visualization. This is the main entry point - a default method on the Reader trait.

**What happens during execution:**

1. Parses the query (SQL + VISUALISE portions)
2. Executes the main SQL query using the reader
3. Resolves wildcards (`VISUALISE *`) against actual columns
4. Merges global mappings into each layer
5. Executes layer-specific queries (filters, stats)
6. Injects constant values as synthetic columns
7. Computes aesthetic labels from column names

**Arguments:**

- `query` - The full ggsql query string

**Returns:**

- `Ok(Spec)` - Ready for rendering
- `Err(GgsqlError)` - Parse, validation, or execution error

**Example:**

```rust
use ggsql::reader::{DuckDBReader, Reader};
use ggsql::writer::{VegaLiteWriter, Writer};

let reader = DuckDBReader::from_connection_string("duckdb://memory")?;
let spec = reader.execute(
    "SELECT x, y FROM data VISUALISE x, y DRAW point"
)?;

// Access metadata
println!("Rows: {}", spec.metadata().rows);
println!("Columns: {:?}", spec.metadata().columns);

// Render to Vega-Lite
let writer = VegaLiteWriter::new();
let result = writer.render(&spec)?;
```

**Error Conditions:**

- Parse error in SQL or VISUALISE portion
- SQL execution failure
- Missing required aesthetics
- Invalid geom type
- Multiple VISUALISE statements (not yet supported)

---

### `validate`

```rust
pub fn validate(query: &str) -> Result<Validated>
```

Validate query syntax and semantics without executing SQL. This function combines query parsing and validation into a single operation.

**What is validated:**

- Syntax (parsing)
- Required aesthetics for each geom type
- Valid scale types (linear, log10, date, etc.)
- Valid project types and properties
- Valid geom types
- Valid aesthetic names
- Valid SETTING parameters

**Arguments:**

- `query` - The full ggsql query string (SQL + VISUALISE)

**Returns:**

- `Ok(Validated)` - Validation results with query inspection methods
- `Err(GgsqlError)` - Internal error

**Example:**

```rust
use ggsql::validate;

let validated = validate("SELECT x, y FROM data VISUALISE x, y DRAW point")?;

// Check validity
if !validated.valid() {
    for error in validated.errors() {
        eprintln!("Error: {}", error.message);
    }
}

// Inspect query structure
if validated.has_visual() {
    println!("SQL: {}", validated.sql());
    println!("Visual: {}", validated.visual());
}
```

**Notes:**

- Does not execute SQL
- Does not resolve wildcards or global mappings
- Cannot validate column existence (requires data)
- Returns all errors, not just the first one
- CST available via `tree()` for advanced inspection

---

## Type Reference

### `Validated`

Result of validating a query (syntax + semantics, no SQL execution).

```rust
pub struct Validated {
    // All fields private
}
```

**Methods:**

| Method       | Signature                                    | Description                        |
| ------------ | -------------------------------------------- | ---------------------------------- |
| `has_visual` | `fn has_visual(&self) -> bool`               | Whether query contains VISUALISE   |
| `sql`        | `fn sql(&self) -> &str`                      | The SQL portion (before VISUALISE) |
| `visual`     | `fn visual(&self) -> &str`                   | The VISUALISE portion (raw text)   |
| `tree`       | `fn tree(&self) -> Option<&Tree>`            | CST for advanced inspection        |
| `valid`      | `fn valid(&self) -> bool`                    | Whether query is valid             |
| `errors`     | `fn errors(&self) -> &[ValidationError]`     | Validation errors                  |
| `warnings`   | `fn warnings(&self) -> &[ValidationWarning]` | Validation warnings                |

**Example:**

```rust
let validated = ggsql::validate("SELECT 1 as x VISUALISE DRAW point MAPPING x AS x, y AS y")?;

// Check validity
if !validated.valid() {
    for error in validated.errors() {
        eprintln!("Error: {}", error.message);
    }
}

// Inspect query structure
assert!(validated.has_visual());
assert_eq!(validated.sql(), "SELECT 1 as x");
assert!(validated.visual().starts_with("VISUALISE"));

// CST access for advanced use cases
if let Some(tree) = validated.tree() {
    println!("Root node: {}", tree.root_node().kind());
}
```

---

### `Spec`

Result of executing a ggsql query, ready for rendering.

#### Rendering

Use `writer.render(&spec)` to generate output.

**Example:**

```rust
let writer = VegaLiteWriter::new();
let json = writer.render(&spec)?;
println!("{}", json);
```

#### Plot Access Methods

| Method        | Signature                        | Description                     |
| ------------- | -------------------------------- | ------------------------------- |
| `plot`        | `fn plot(&self) -> &Plot`        | Get resolved plot specification |
| `layer_count` | `fn layer_count(&self) -> usize` | Number of layers                |

**Example:**

```rust
println!("Layers: {}", spec.layer_count());

let plot = spec.plot();
for (i, layer) in plot.layers.iter().enumerate() {
    println!("Layer {}: {:?}", i, layer.geom);
}
```

#### Metadata Methods

| Method     | Signature                         | Description                |
| ---------- | --------------------------------- | -------------------------- |
| `metadata` | `fn metadata(&self) -> &Metadata` | Get visualization metadata |

**Example:**

```rust
let meta = spec.metadata();
println!("Rows: {}", meta.rows);
println!("Columns: {:?}", meta.columns);
println!("Layer count: {}", meta.layer_count);
```

#### Data Access Methods

| Method       | Signature                                              | Description                     |
| ------------ | ------------------------------------------------------ | ------------------------------- |
| `layer_data` | `fn layer_data(&self, i: usize) -> Option<&DataFrame>` | Layer-specific data             |
| `stat_data`  | `fn stat_data(&self, i: usize) -> Option<&DataFrame>`  | Stat transform results          |
| `data`       | `fn data(&self) -> &HashMap<String, DataFrame>`        | Raw data map access             |

**Example:**

```rust
// Layer data (first layer)
if let Some(df) = spec.layer_data(0) {
    println!("Layer 0 data: {} rows", df.height());
}

// Layer-specific data (from FILTER or FROM clause)
if let Some(df) = spec.layer_data(0) {
    println!("Layer 0 has filtered data: {} rows", df.height());
}

// Stat data (histogram bins, density estimates, etc.)
if let Some(df) = spec.stat_data(1) {
    println!("Layer 1 stat data: {} rows", df.height());
}
```

#### Query Introspection Methods

| Method      | Signature                                       | Description                      |
| ----------- | ----------------------------------------------- | -------------------------------- |
| `sql`       | `fn sql(&self) -> &str`                         | Main SQL query that was executed |
| `visual`    | `fn visual(&self) -> &str`                      | Raw VISUALISE text               |
| `layer_sql` | `fn layer_sql(&self, i: usize) -> Option<&str>` | Layer filter/source query        |
| `stat_sql`  | `fn stat_sql(&self, i: usize) -> Option<&str>`  | Stat transform query             |

**Example:**

```rust
// Main query
println!("SQL: {}", spec.sql());
println!("Visual: {}", spec.visual());

// Per-layer queries
for i in 0..spec.layer_count() {
    if let Some(sql) = spec.layer_sql(i) {
        println!("Layer {} filter: {}", i, sql);
    }
    if let Some(sql) = spec.stat_sql(i) {
        println!("Layer {} stat: {}", i, sql);
    }
}
```

#### Warnings Method

| Method     | Signature                                    | Description                        |
| ---------- | -------------------------------------------- | ---------------------------------- |
| `warnings` | `fn warnings(&self) -> &[ValidationWarning]` | Validation warnings from execution |

**Example:**

```rust
let spec = reader.execute(query)?;

// Check for warnings
if !spec.warnings().is_empty() {
    for warning in spec.warnings() {
        eprintln!("Warning: {}", warning.message);
    }
}

// Continue with rendering
let writer = VegaLiteWriter::new();
let json = writer.render(&spec)?;
```

---

### `Metadata`

Information about the prepared visualization.

```rust
pub struct Metadata {
    pub rows: usize,           // Rows in primary data source
    pub columns: Vec<String>,  // Column names
    pub layer_count: usize,    // Number of layers in the plot
}
```

---

### `ValidationError`

A validation error (fatal issue).

```rust
pub struct ValidationError {
    pub message: String,
    pub location: Option<Location>,
}
```

---

### `ValidationWarning`

A validation warning (non-fatal issue).

```rust
pub struct ValidationWarning {
    pub message: String,
    pub location: Option<Location>,
}
```

---

### `Location`

Location within a query string.

```rust
pub struct Location {
    pub line: usize,    // 0-based line number
    pub column: usize,  // 0-based column number
}
```

---

## Reader Trait & Implementations

### `Reader` Trait

```rust
pub trait Reader {
    /// Execute a SQL query and return a DataFrame
    fn execute_sql(&self, sql: &str) -> Result<DataFrame>;

    /// Register a DataFrame as a queryable table
    fn register(&self, name: &str, df: DataFrame, replace: bool) -> Result<()>;

    /// Unregister a previously registered table
    fn unregister(&self, name: &str) -> Result<()>;
}
```

---

## Writer Trait & Implementations

### `Writer` Trait

```rust
pub trait Writer {
    /// What this writer produces — `String` for Vega-Lite JSON and SVG,
    /// `Vec<u8>` for the binary formats
    type Output;

    /// Build the writer from key–value options (see `WriterOptions`)
    fn from_options(options: &WriterOptions) -> Result<Self> where Self: Sized;

    /// Render a plot specification and its data to the output format
    fn write(&self, spec: &Plot, data: &HashMap<String, DataFrame>) -> Result<Self::Output>;

    /// Check whether a spec can be rendered by this writer, without rendering it
    fn validate(&self, spec: &Plot) -> Result<()>;

    /// Render a prepared `Spec` from `reader.execute()` — the usual entry point
    fn render(&self, spec: &Spec) -> Result<Self::Output>;
}
```

---

### `WriterOptions`

Free-form key–value configuration for a writer, for callers that collect settings
from a user rather than in code (the CLI's repeatable `--writer-option
key=value`). Keys are normalised: trimmed, lowercased, `-` folded to `_`.

```rust
let options = WriterOptions::parse(["width=1600", "height=1200", "units=px"])?;
let svg = SvgWriter::from_options(&options)?.render(&spec)?;

// One string may carry several options, separated by `;`. Equivalent to the above:
let options = WriterOptions::parse(["width=1600;height=1200;units=px"])?;

// Or in code, without going through strings:
let options = WriterOptions::new().set("dpi", "150");
```

`;` is the only separator — `,` is not, since values contain commas
(`background=rgba(0,0,0,0)`).

| Method | Purpose |
| --- | --- |
| `parse(pairs)` | Build from `key=value` strings, `;`-separated within a string; errors on a missing `=` |
| `new()` / `set(key, value)` | Build programmatically |
| `get(key)` | Raw value, if supplied |
| `number(key)` | Value as a finite `f64`, erroring with the option's name |
| `boolean(key)` | Value as a `bool`, accepting `true`/`false`/`1`/`0`/`yes`/`no`/`on`/`off` |
| `one_of(key, allowed)` | Value checked against a closed set |
| `reject_unknown(known)` | Error naming keys the writer doesn't understand |
| `is_empty()` | Whether any option was supplied |

Which keys a writer accepts is the writer's own business:
`VegaLiteWriter` takes none, `PngWriter` takes `width`, `height`, `units`,
`dpi`, and `background`.