ggsql 0.4.1

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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! Query validation without SQL execution.
//!
//! This module provides query syntax and semantic validation without executing
//! any SQL. Use this for IDE integration, syntax checking, and query inspection.

use crate::parser;
use crate::Result;

// ============================================================================
// Core Types
// ============================================================================

/// Result of `validate()` - query inspection and validation without SQL execution.
pub struct Validated {
    sql: String,
    visual: String,
    has_visual: bool,
    tree: Option<tree_sitter::Tree>,
    valid: bool,
    errors: Vec<ValidationError>,
    warnings: Vec<ValidationWarning>,
}

impl Validated {
    /// Whether the query contains a VISUALISE clause.
    pub fn has_visual(&self) -> bool {
        self.has_visual
    }

    /// The SQL portion (before VISUALISE).
    pub fn sql(&self) -> &str {
        &self.sql
    }

    /// The VISUALISE portion (raw text).
    pub fn visual(&self) -> &str {
        &self.visual
    }

    /// CST for advanced inspection.
    pub fn tree(&self) -> Option<&tree_sitter::Tree> {
        self.tree.as_ref()
    }

    /// Whether the query is valid (no errors).
    pub fn valid(&self) -> bool {
        self.valid
    }

    /// Validation errors.
    pub fn errors(&self) -> &[ValidationError] {
        &self.errors
    }

    /// Validation warnings.
    pub fn warnings(&self) -> &[ValidationWarning] {
        &self.warnings
    }
}

/// A validation error (fatal).
#[derive(Debug, Clone)]
pub struct ValidationError {
    pub message: String,
    pub location: Option<Location>,
}

/// A validation warning (non-fatal).
#[derive(Debug, Clone)]
pub struct ValidationWarning {
    pub message: String,
    pub location: Option<Location>,
}

/// Location within a query string (0-based).
#[derive(Debug, Clone)]
pub struct Location {
    pub line: usize,
    pub column: usize,
}

// ============================================================================
// Validation Function
// ============================================================================

fn has_error_ancestor(node: &tree_sitter::Node) -> bool {
    let mut cur = node.parent();
    while let Some(p) = cur {
        if p.is_error() {
            return true;
        }
        cur = p.parent();
    }
    false
}

/// Validate query syntax and semantics without executing SQL.
pub fn validate(query: &str) -> Result<Validated> {
    let mut errors = Vec::new();
    let warnings = Vec::new();

    // Parse once and create SourceTree
    let source_tree = match parser::SourceTree::new(query) {
        Ok(st) => st,
        Err(e) => {
            // Parse error - return as validation error
            errors.push(ValidationError {
                message: e.to_string(),
                location: None,
            });
            return Ok(Validated {
                sql: String::new(),
                visual: String::new(),
                has_visual: false,
                tree: None,
                valid: false,
                errors,
                warnings,
            });
        }
    };

    // Extract SQL and viz portions using existing tree
    let sql_part = source_tree.extract_sql().unwrap_or_default();
    let viz_part = source_tree.extract_visualise().unwrap_or_default();

    let root = source_tree.root();
    let visualise_stmt = source_tree.find_node(&root, "(visualise_statement) @viz");
    let has_visual = visualise_stmt.is_some();

    if let Err(e) = source_tree.validate() {
        // The lexer always tokenises VISUALISE / VISUALIZE as
        // `visualise_keyword` (token prec 10 in grammar.js), so the keyword
        // survives even when parsing fails. We give a ggsql-aware message
        // only when the parse error lies on the VISUALISE side: either no
        // visualise_statement was recovered (keyword stranded in an ERROR
        // node) or one was recovered as a fragment under an ERROR ancestor
        // (partial recovery — common when a mapping holds a SQL expression
        // and the parser rolls forward into the SQL portion). When the
        // visualise_statement is a clean top-level child of `query`, the
        // error is in the SQL portion and the generic message is more honest.
        let kw_pos = source_tree
            .find_node(&root, "(visualise_keyword) @kw")
            .map(|n| n.start_position());
        let visualise_side_failed = match &visualise_stmt {
            Some(node) => node.has_error() || has_error_ancestor(node),
            None => kw_pos.is_some(),
        };
        let (message, location) = if visualise_side_failed {
            (
                "VISUALISE clause was not recognized. Mappings accept column \
                 names only — not SQL expressions like CAST() or function \
                 calls. Move data transformations to the SELECT clause and \
                 reference the resulting column by name in VISUALISE."
                    .to_string(),
                kw_pos.map(|p| Location {
                    line: p.row,
                    column: p.column,
                }),
            )
        } else {
            (e.to_string(), None)
        };
        errors.push(ValidationError { message, location });
        return Ok(Validated {
            sql: sql_part,
            visual: viz_part,
            has_visual,
            tree: Some(source_tree.tree),
            valid: false,
            errors,
            warnings,
        });
    }

    // Genuine SQL-only query (no parse errors, no VISUALISE clause).
    if !has_visual {
        return Ok(Validated {
            sql: sql_part,
            visual: viz_part,
            has_visual: false,
            tree: None,
            valid: true,
            errors,
            warnings,
        });
    }

    // Build AST from existing tree for validation
    let plots = match parser::build_ast(&source_tree) {
        Ok(p) => p,
        Err(e) => {
            errors.push(ValidationError {
                message: e.to_string(),
                location: None,
            });
            return Ok(Validated {
                sql: sql_part,
                visual: viz_part,
                has_visual,
                tree: Some(source_tree.tree),
                valid: false,
                errors,
                warnings,
            });
        }
    };

    // Validate the single plot (we only support one VISUALISE statement)
    if let Some(plot) = plots.first() {
        // Validate each layer
        for (layer_idx, layer) in plot.layers.iter().enumerate() {
            let context = format!("Layer {}", layer_idx + 1);

            // Check required aesthetics
            // Note: Without schema data, we can only check if mappings exist,
            // not if the columns are valid. We skip this check for wildcards
            // (either layer or global).
            let is_annotation = matches!(
                layer.source,
                Some(crate::plot::types::DataSource::Annotation)
            );
            let has_wildcard =
                layer.mappings.wildcard || (!is_annotation && plot.global_mappings.wildcard);
            if !has_wildcard {
                // Merge global mappings into a temporary copy for validation
                // (mirrors execution-time merge, layer takes precedence)
                let mut merged = layer.clone();
                if !is_annotation {
                    for (aesthetic, value) in &plot.global_mappings.aesthetics {
                        merged
                            .mappings
                            .aesthetics
                            .entry(aesthetic.clone())
                            .or_insert(value.clone());
                    }
                }
                if let Err(e) = merged.validate_mapping(&plot.aesthetic_context, false) {
                    errors.push(ValidationError {
                        message: format!("{}: {}", context, e),
                        location: None,
                    });
                }
            }

            // Validate SETTING parameters
            if let Err(e) = layer.validate_settings() {
                errors.push(ValidationError {
                    message: format!("{}: {}", context, e),
                    location: None,
                });
            }

            // The aggregate setting is validated in isolation here so the
            // standalone validate path (which doesn't run the stat) still
            // catches malformed `aggregate` values and unmapped/duplicate
            // targets. The execute path skips this; `stat_aggregate::apply`
            // parses + reports there.
            if let Err(e) = layer.validate_aggregate_setting(plot.aesthetic_context.as_ref()) {
                errors.push(ValidationError {
                    message: format!("{}: {}", context, e),
                    location: None,
                });
            }
        }
    }

    Ok(Validated {
        sql: sql_part,
        visual: viz_part,
        has_visual,
        tree: Some(source_tree.tree),
        valid: errors.is_empty(),
        errors,
        warnings,
    })
}

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

    #[test]
    fn test_validate_with_visual() {
        let validated =
            validate("SELECT 1 as x, 2 as y VISUALISE DRAW point MAPPING x AS x, y AS y").unwrap();
        assert!(validated.has_visual());
        assert_eq!(validated.sql(), "SELECT 1 as x, 2 as y");
        assert!(validated.visual().starts_with("VISUALISE"));
        assert!(validated.tree().is_some());
        assert!(validated.valid());
    }

    #[test]
    fn test_validate_without_visual() {
        let validated = validate("SELECT 1 as x, 2 as y").unwrap();
        assert!(!validated.has_visual());
        assert_eq!(validated.sql(), "SELECT 1 as x, 2 as y");
        assert!(validated.visual().is_empty());
        assert!(validated.tree().is_none());
        assert!(validated.valid());
    }

    #[test]
    fn test_validate_valid_query() {
        let validated =
            validate("SELECT 1 as x, 2 as y VISUALISE DRAW point MAPPING x AS x, y AS y").unwrap();
        assert!(
            validated.valid(),
            "Expected valid query: {:?}",
            validated.errors()
        );
        assert!(validated.errors().is_empty());
    }

    #[test]
    fn test_validate_missing_required_aesthetic() {
        // Line requires both x and y; mapping only x is invalid.
        let validated =
            validate("SELECT 1 as x, 2 as y VISUALISE DRAW line MAPPING x AS x").unwrap();
        assert!(!validated.valid());
        assert!(!validated.errors().is_empty());
        assert!(validated.errors()[0].message.contains("y"));
    }

    #[test]
    fn test_validate_syntax_error() {
        let validated = validate("SELECT 1 VISUALISE DRAW invalidgeom").unwrap();
        assert!(!validated.valid());
        assert!(!validated.errors().is_empty());
    }

    #[test]
    fn test_validate_sql_and_visual_content() {
        let query = "SELECT 1 as x, 2 as y VISUALISE DRAW point MAPPING x AS x, y AS y DRAW line MAPPING x AS x, y AS y";
        let validated = validate(query).unwrap();

        assert!(validated.has_visual());
        assert_eq!(validated.sql(), "SELECT 1 as x, 2 as y");
        assert!(validated.visual().contains("DRAW point"));
        assert!(validated.visual().contains("DRAW line"));
        assert!(validated.valid());
    }

    #[test]
    fn test_validate_sql_only() {
        let query = "SELECT 1 as x, 2 as y";
        let validated = validate(query).unwrap();

        // SQL-only queries should be valid (just syntax check)
        assert!(validated.valid());
        assert!(validated.errors().is_empty());
    }

    #[test]
    fn test_validate_color_aesthetic_on_line() {
        // color should be valid on line geom (has stroke)
        let validated = validate(
            "SELECT 1 as x, 2 as y VISUALISE DRAW line MAPPING x AS x, y AS y, region AS color",
        )
        .unwrap();
        assert!(
            validated.valid(),
            "color should be accepted on line geom: {:?}",
            validated.errors()
        );
    }

    #[test]
    fn test_validate_color_aesthetic_on_point() {
        // color should be valid on point geom (has stroke + fill)
        let validated = validate(
            "SELECT 1 as x, 2 as y VISUALISE DRAW point MAPPING x AS x, y AS y, cat AS color",
        )
        .unwrap();
        assert!(
            validated.valid(),
            "color should be accepted on point geom: {:?}",
            validated.errors()
        );
    }

    #[test]
    fn test_validate_colour_spelling() {
        // British spelling 'colour' should work (normalized by parser to 'color')
        let validated = validate(
            "SELECT 1 as x, 2 as y VISUALISE DRAW line MAPPING x AS x, y AS y, region AS colour",
        )
        .unwrap();
        assert!(
            validated.valid(),
            "colour (British) should be accepted: {:?}",
            validated.errors()
        );
    }

    #[test]
    fn test_validate_global_color_mapping() {
        // Global color mapping should validate correctly
        let validated =
            validate("SELECT 1 as x, 2 as y VISUALISE x AS x, y AS y, region AS color DRAW line")
                .unwrap();
        assert!(
            validated.valid(),
            "global color mapping should be accepted: {:?}",
            validated.errors()
        );
    }

    // Issue #256: SQL expressions in VISUALISE mappings used to be silently
    // consumed as SQL, with validate() reporting valid=true and has_visual=false.
    // The fix detects a stray visualise_keyword node (one that didn't make it
    // into a visualise_statement) and emits an actionable error.

    #[test]
    fn test_validate_cast_in_visualise_mapping() {
        let query = "SELECT sex, survived, COUNT(*) AS n FROM titanic GROUP BY sex, survived\n\
                     VISUALISE sex AS x, n AS y, CAST(survived AS VARCHAR) AS fill\n\
                     DRAW bar";
        let validated = validate(query).unwrap();
        assert!(!validated.valid());
        assert!(!validated.errors().is_empty());
        let msg = &validated.errors()[0].message;
        assert!(
            msg.contains("VISUALISE") && msg.contains("column"),
            "expected helpful message, got: {msg}"
        );
        assert!(validated.errors()[0].location.is_some());
    }

    #[test]
    fn test_validate_function_call_in_visualise_mapping() {
        let query = "SELECT t, v FROM data VISUALISE date_trunc('day', t) AS x, v AS y DRAW line";
        let validated = validate(query).unwrap();
        assert!(!validated.valid());
        assert!(!validated.errors().is_empty());
        assert!(validated.errors()[0].message.contains("VISUALISE"));
    }

    #[test]
    fn test_validate_lowercase_visualise_keyword_with_expression() {
        let query = "SELECT a, b FROM t visualise cast(a as varchar) as x, b as y draw point";
        let validated = validate(query).unwrap();
        assert!(!validated.valid());
        assert!(!validated.errors().is_empty());
    }

    #[test]
    fn test_validate_us_visualize_spelling_with_expression() {
        let query = "SELECT a, b FROM t VISUALIZE CAST(a AS VARCHAR) AS x, b AS y DRAW point";
        let validated = validate(query).unwrap();
        assert!(!validated.valid());
        assert!(!validated.errors().is_empty());
    }

    #[test]
    fn test_validate_sql_side_error_does_not_blame_visualise() {
        // When the parse error is in the SQL portion but the VISUALISE clause
        // is fully recovered, we must not emit the "VISUALISE clause was not
        // recognized" message — the VISUALISE clause is fine.
        let query = "SELECT @@@ FROM t VISUALISE a AS x, b AS y DRAW point";
        let validated = validate(query).unwrap();
        assert!(!validated.valid());
        assert!(!validated.errors().is_empty());
        let msg = &validated.errors()[0].message;
        assert!(
            !msg.contains("VISUALISE clause was not recognized"),
            "SQL-side error should not be reported as a VISUALISE error, got: {msg}"
        );
    }

    #[test]
    fn test_validate_visualise_in_string_literal_is_valid() {
        // VISUALISE inside a string literal must NOT trigger the new error —
        // tree-sitter classifies it as part of a string node.
        let validated = validate("SELECT 'VISUALISE' AS s").unwrap();
        assert!(
            validated.valid(),
            "string literal containing VISUALISE should be valid: {:?}",
            validated.errors()
        );
        assert!(!validated.has_visual());
    }

    #[test]
    fn test_validate_visualise_in_comment_is_valid() {
        // VISUALISE inside a comment must NOT trigger the new error.
        let validated = validate("SELECT 1 AS x -- VISUALISE here\n").unwrap();
        assert!(
            validated.valid(),
            "comment containing VISUALISE should be valid: {:?}",
            validated.errors()
        );
        assert!(!validated.has_visual());
    }
}