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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
//! Tree-sitter source tree wrapper with declarative query support.
//!
//! The `SourceTree` struct wraps a tree-sitter parse tree along with the source text
//! and language, providing high-level query operations for tree traversal and text extraction.

use crate::{GgsqlError, Result};
use tree_sitter::{Language, Node, Parser, Query, QueryCursor, StreamingIterator, Tree};

/// The source tree - holds a parsed syntax tree, source text, and language together.
/// Like Yggdrasil, it connects all parsing operations with a single root.
#[derive(Debug)]
pub struct SourceTree<'a> {
    pub tree: Tree,
    pub source: &'a str,
    pub language: Language,
}

impl<'a> SourceTree<'a> {
    /// Parse source and create a new SourceTree
    pub fn new(source: &'a str) -> Result<Self> {
        let language = tree_sitter_ggsql::language();

        let mut parser = Parser::new();
        parser
            .set_language(&language)
            .map_err(|e| GgsqlError::InternalError(format!("Failed to set language: {}", e)))?;

        let tree = parser
            .parse(source, None)
            .ok_or_else(|| GgsqlError::ParseError("Failed to parse query".to_string()))?;

        let source_tree = Self {
            tree,
            source,
            language,
        };

        // Reject ambiguous double-FROM: `FROM a VISUALISE FROM b …` has two
        // data sources for one statement. Caught here (rather than at extract
        // time) so extract_sql returns a plain Option and every consumer that
        // already handles new()'s Result gets the check for free.
        source_tree.check_no_double_from()?;

        Ok(source_tree)
    }

    fn check_no_double_from(&self) -> Result<()> {
        let root = self.root();
        let has_sql_from = self
            .find_node(&root, "(sql_statement (from_statement) @stmt)")
            .is_some();
        let has_viz_from = self
            .find_node(&root, "(visualise_statement (from_clause (table_ref) @t))")
            .is_some();
        if has_sql_from && has_viz_from {
            return Err(GgsqlError::ParseError(
                "VISUALISE has two FROM clauses (one before VISUALISE and one after). \
                 Use only one."
                    .to_string(),
            ));
        }
        Ok(())
    }

    /// Validate that the parse tree has no errors
    pub fn validate(&self) -> Result<()> {
        if self.tree.root_node().has_error() {
            return Err(GgsqlError::ParseError(
                "Parse tree contains errors".to_string(),
            ));
        }
        Ok(())
    }

    /// Get the root node
    pub fn root(&self) -> Node<'_> {
        self.tree.root_node()
    }

    /// Extract text from a node
    pub fn get_text(&self, node: &Node) -> String {
        self.source[node.start_byte()..node.end_byte()].to_string()
    }

    /// Find all nodes matching a tree-sitter query
    pub fn find_nodes<'b>(&self, node: &Node<'b>, query_source: &str) -> Vec<Node<'b>> {
        let query = match Query::new(&self.language, query_source) {
            Ok(q) => q,
            Err(_) => return Vec::new(),
        };

        let mut cursor = QueryCursor::new();
        let mut matches = cursor.matches(&query, *node, self.source.as_bytes());

        let mut results = Vec::new();
        while let Some(match_result) = matches.next() {
            for capture in match_result.captures {
                results.push(capture.node);
            }
        }
        results
    }

    /// Find first node matching query
    pub fn find_node<'b>(&self, node: &Node<'b>, query_source: &str) -> Option<Node<'b>> {
        let query = match Query::new(&self.language, query_source) {
            Ok(q) => q,
            Err(_) => return None,
        };

        let mut cursor = QueryCursor::new();
        let mut matches = cursor.matches(&query, *node, self.source.as_bytes());

        // Return the first capture immediately without collecting all results
        if let Some(match_result) = matches.next() {
            if let Some(capture) = match_result.captures.first() {
                return Some(capture.node);
            }
        }
        None
    }

    /// Find first node text matching query
    pub fn find_text(&self, node: &Node, query: &str) -> Option<String> {
        self.find_node(node, query).map(|n| self.get_text(&n))
    }

    /// Find all node texts matching query
    pub fn find_texts(&self, node: &Node, query: &str) -> Vec<String> {
        self.find_nodes(node, query)
            .iter()
            .map(|n| self.get_text(n))
            .collect()
    }

    /// Extract the SQL portion of the query (before VISUALISE).
    ///
    /// Two rewrites happen here so the returned SQL is always something a
    /// plain SQL reader can execute:
    ///
    /// - DuckDB-style FROM-first: the grammar parses bare `FROM t` as a
    ///   `from_statement`. Each such statement is rewritten by prepending
    ///   `SELECT * ` — so `FROM sales VISUALISE …` becomes
    ///   `SELECT * FROM sales`.
    /// - `VISUALISE FROM <source>`: the FROM appears on the VISUALISE clause.
    ///   We append `SELECT * FROM <source>` to the SQL so the reader sees an
    ///   executable query.
    ///
    /// Returns `None` if there's no SQL portion and no VISUALISE FROM to
    /// inject. The ambiguous double-FROM case (`FROM a VISUALISE FROM b …`)
    /// is rejected in `SourceTree::new`, so any tree reaching here has at
    /// most one of the two FROMs.
    pub fn extract_sql(&self) -> Option<String> {
        let root = self.root();

        // Check if there's any VISUALISE statement
        if self
            .find_node(&root, "(visualise_statement) @viz")
            .is_none()
        {
            // No VISUALISE at all - return entire source as SQL
            return Some(self.source.to_string());
        }

        // Find sql_portion node and extract its text
        let sql_portion_node = self.find_node(&root, "(sql_portion) @sql");
        let mut sql_text = sql_portion_node
            .map(|node| self.get_text(&node))
            .unwrap_or_default();

        // DuckDB-style FROM-first: the grammar recognizes bare `FROM t` as an
        // sql_statement variant. Rewrite each such occurrence by prepending
        // `SELECT * `.
        if let Some(sql_portion) = sql_portion_node {
            let from_stmts = self.find_nodes(&sql_portion, "(from_statement) @from_stmt");
            if !from_stmts.is_empty() {
                let portion_start = sql_portion.start_byte();
                let portion_end = sql_portion.end_byte();
                let mut stmts: Vec<Node> = from_stmts;
                stmts.sort_by_key(|n| n.start_byte());
                let mut out = String::with_capacity(sql_text.len() + stmts.len() * 9);
                let mut cursor = portion_start;
                for stmt in stmts {
                    let s = stmt.start_byte();
                    out.push_str(&self.source[cursor..s]);
                    out.push_str("SELECT * ");
                    cursor = s;
                }
                out.push_str(&self.source[cursor..portion_end]);
                sql_text = out;
            }
        }

        // VISUALISE FROM <source>: append "SELECT * FROM <source>".
        let viz_from = self.find_text(
            &root,
            r#"
                (visualise_statement
                  (from_clause
                    (table_ref) @table))
            "#,
        );

        if let Some(from_identifier) = viz_from {
            let result = if sql_text.trim().is_empty() {
                format!("SELECT * FROM {}", from_identifier)
            } else {
                format!("{} SELECT * FROM {}", sql_text.trim(), from_identifier)
            };
            Some(result)
        } else {
            let trimmed = sql_text.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some(trimmed.to_string())
            }
        }
    }

    /// Extract the VISUALISE portion of the query (from first VISUALISE onwards)
    ///
    /// Returns the raw text of all VISUALISE statements
    pub fn extract_visualise(&self) -> Option<String> {
        let root = self.root();

        // Find byte offset of first VISUALISE
        let viz_start = self
            .find_node(&root, "(visualise_statement) @viz")
            .map(|node| node.start_byte())?;

        // Extract viz text from first VISUALISE onwards
        let viz_text = &self.source[viz_start..];
        Some(viz_text.trim().to_string())
    }
}

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

    #[test]
    fn test_extract_sql_simple() {
        let query = "SELECT * FROM data VISUALISE  DRAW point MAPPING x AS x, y AS y";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        assert_eq!(sql, "SELECT * FROM data");

        let viz = tree.extract_visualise().unwrap();
        assert!(viz.starts_with("VISUALISE"));
        assert!(viz.contains("DRAW point"));
    }

    #[test]
    fn test_extract_sql_case_insensitive() {
        let query = "SELECT * FROM data visualise x, y DRAW point";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        assert_eq!(sql, "SELECT * FROM data");

        let viz = tree.extract_visualise().unwrap();
        assert!(viz.starts_with("visualise"));
    }

    #[test]
    fn test_extract_sql_preserves_jinja_ref() {
        let query = "SELECT order_date, region, revenue FROM {{ ref('fct_orders') }}\nVISUALISE order_date AS x, revenue AS y, region AS color\nDRAW point";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        assert_eq!(
            sql,
            "SELECT order_date, region, revenue FROM {{ ref('fct_orders') }}"
        );
    }

    #[test]
    fn test_extract_sql_no_visualise() {
        let query = "SELECT * FROM data WHERE x > 5";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        assert_eq!(sql, query);

        let viz = tree.extract_visualise();
        assert!(viz.is_none());
    }

    #[test]
    fn test_extract_sql_visualise_from_no_sql() {
        let query = "VISUALISE FROM mtcars  DRAW point MAPPING mpg AS x, hp AS y";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        // Should inject SELECT * FROM mtcars
        assert_eq!(sql, "SELECT * FROM mtcars");

        let viz = tree.extract_visualise().unwrap();
        assert!(viz.starts_with("VISUALISE FROM mtcars"));
    }

    #[test]
    fn test_extract_sql_visualise_from_jinja_ref() {
        let query = "VISUALISE FROM {{ ref('fct_orders') }} DRAW point MAPPING x AS x, y AS y";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        assert_eq!(sql, "SELECT * FROM {{ ref('fct_orders') }}");

        let viz = tree.extract_visualise().unwrap();
        assert!(viz.starts_with("VISUALISE FROM {{ ref('fct_orders') }}"));
    }

    #[test]
    fn test_extract_sql_visualise_from_with_cte() {
        let query =
            "WITH cte AS (SELECT * FROM x) VISUALISE FROM cte DRAW point MAPPING a AS x, b AS y";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        // Should inject SELECT * FROM cte after the WITH
        assert!(sql.contains("WITH cte AS (SELECT * FROM x)"));
        assert!(sql.contains("SELECT * FROM cte"));

        let viz = tree.extract_visualise().unwrap();
        assert!(viz.starts_with("VISUALISE FROM cte"));
    }

    #[test]
    fn test_extract_sql_visualise_from_after_create() {
        let query = "CREATE TABLE x AS SELECT 1; VISUALISE FROM x";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        assert!(sql.contains("CREATE TABLE x AS SELECT 1;"));
        assert!(sql.contains("SELECT * FROM x"));

        let viz = tree.extract_visualise().unwrap();
        assert!(viz.starts_with("VISUALISE FROM x"));

        // Without semicolon, the visualise statement should also be recognised
        let query2 = "CREATE TABLE x AS SELECT 1 VISUALISE FROM x";
        let tree2 = SourceTree::new(query2).unwrap();

        let sql2 = tree2.extract_sql().unwrap();
        assert!(sql2.contains("CREATE TABLE x AS SELECT 1"));
        assert!(sql2.contains("SELECT * FROM x"));

        let viz2 = tree2.extract_visualise().unwrap();
        assert!(viz2.starts_with("VISUALISE FROM x"));
    }

    #[test]
    fn test_extract_sql_visualise_from_after_insert() {
        let query = "INSERT INTO x VALUES (1) VISUALISE FROM x DRAW";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        assert!(sql.contains("INSERT"));

        let viz = tree.extract_visualise().unwrap();
        assert!(viz.contains("DRAW"));
    }

    #[test]
    fn test_extract_sql_no_injection_with_select() {
        let query = "SELECT * FROM x VISUALISE DRAW point MAPPING a AS x, b AS y";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        // Should NOT inject anything - just extract SQL normally
        assert_eq!(sql, "SELECT * FROM x");
        assert!(!sql.contains("SELECT * FROM SELECT")); // Make sure we didn't double-inject
    }

    // ========================================================================
    // FROM-first (DuckDB-style) tests
    // ========================================================================

    #[test]
    fn test_extract_sql_from_first_simple() {
        let query = "FROM mtcars VISUALISE DRAW point MAPPING mpg AS x, hp AS y";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        assert!(sql.contains("SELECT * FROM mtcars"));

        let viz = tree.extract_visualise().unwrap();
        assert!(viz.starts_with("VISUALISE"));
    }

    #[test]
    fn test_extract_sql_from_first_with_where() {
        let query = "FROM sales WHERE year = 2024 VISUALISE DRAW point MAPPING x AS x, y AS y";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        assert!(sql.contains("SELECT * FROM sales WHERE year = 2024"));
    }

    #[test]
    fn test_extract_sql_from_first_with_cte() {
        let query =
            "WITH cte AS (SELECT * FROM x) FROM cte VISUALISE DRAW point MAPPING a AS x, b AS y";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        assert!(sql.contains("WITH cte AS (SELECT * FROM x)"));
        assert!(sql.contains("SELECT * FROM cte"));
    }

    #[test]
    fn test_extract_sql_from_first_after_create() {
        let query =
            "CREATE TABLE x AS SELECT 1; FROM x VISUALISE DRAW point MAPPING a AS x, b AS y";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        assert!(sql.contains("CREATE TABLE x AS SELECT 1"));
        assert!(sql.contains("SELECT * FROM x"));
    }

    #[test]
    fn test_extract_sql_from_first_file_path() {
        let query = "FROM 'mtcars.csv' VISUALISE DRAW point MAPPING mpg AS x, hp AS y";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        assert!(sql.contains("SELECT * FROM 'mtcars.csv'"));
    }

    #[test]
    fn test_extract_sql_from_first_jinja_ref() {
        let query = "FROM {{ ref('fct_orders') }} VISUALISE DRAW point MAPPING x AS x, y AS y";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        assert_eq!(sql, "SELECT * FROM {{ ref('fct_orders') }}");
    }

    #[test]
    fn test_extract_sql_from_first_case_insensitive() {
        let query = "from sales visualise DRAW point MAPPING x AS x, y AS y";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        assert!(sql.contains("SELECT * from sales"));
    }

    #[test]
    fn test_extract_sql_no_rewrite_when_select_precedes_from() {
        // Regression: `SELECT a, b FROM t VISUALISE ...` must NOT trigger
        // SELECT * injection — the FROM belongs to the SELECT.
        let query = "SELECT a, b FROM t VISUALISE DRAW point MAPPING a AS x, b AS y";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        assert_eq!(sql, "SELECT a, b FROM t");
    }

    #[test]
    fn test_double_from_rejected_at_parse() {
        // Leading FROM + VISUALISE FROM is ambiguous and must error at parse
        // time (before any extract_sql call).
        let query = "FROM a VISUALISE FROM b DRAW point MAPPING x AS x, y AS y";
        let err = SourceTree::new(query).unwrap_err();
        let msg = format!("{}", err);
        assert!(
            msg.contains("two FROM clauses"),
            "expected double-FROM rejection, got: {}",
            msg
        );
    }

    #[test]
    fn test_extract_sql_from_first_skips_string_contents() {
        // A FROM inside a string literal in a preceding statement should be
        // parsed as part of the string, not mistaken for a bare FROM.
        let query =
            "CREATE TABLE x AS SELECT 'FROM fake' AS col; FROM x VISUALISE DRAW point MAPPING a AS x, b AS y";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        // Injected SELECT * precedes the real FROM, not the string one.
        assert!(sql.contains("'FROM fake'"));
        assert!(sql.contains("SELECT * FROM x"));
    }

    #[test]
    fn test_extract_sql_from_first_skips_line_comment() {
        let query = "-- FROM fake\nFROM real VISUALISE DRAW point MAPPING a AS x, b AS y";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        assert!(sql.contains("SELECT * FROM real"));
        assert!(!sql.contains("SELECT * -- FROM fake"));
    }

    #[test]
    fn test_extract_sql_visualise_from_file_path_single_quotes() {
        let query = "VISUALISE FROM 'mtcars.csv'  DRAW point MAPPING mpg AS x, hp AS y";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        // Should inject SELECT * FROM 'mtcars.csv' with quotes preserved
        assert_eq!(sql, "SELECT * FROM 'mtcars.csv'");

        let viz = tree.extract_visualise().unwrap();
        assert!(viz.starts_with("VISUALISE FROM 'mtcars.csv'"));
    }

    #[test]
    fn test_extract_sql_visualise_from_file_path_double_quotes() {
        let query =
            r#"VISUALISE FROM "data/sales.parquet"  DRAW bar MAPPING region AS x, total AS y"#;
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        // Should inject SELECT * FROM "data/sales.parquet" with quotes preserved
        assert_eq!(sql, r#"SELECT * FROM "data/sales.parquet""#);

        let viz = tree.extract_visualise().unwrap();
        assert!(viz.starts_with(r#"VISUALISE FROM "data/sales.parquet""#));
    }

    #[test]
    fn test_extract_sql_visualise_from_file_path_with_cte() {
        let query = "WITH prep AS (SELECT * FROM 'raw.csv' WHERE year = 2024) VISUALISE FROM prep  DRAW line MAPPING date AS x, value AS y";
        let tree = SourceTree::new(query).unwrap();

        let sql = tree.extract_sql().unwrap();
        // Should inject SELECT * FROM prep after WITH
        assert!(sql.contains("WITH prep AS"));
        assert!(sql.contains("SELECT * FROM prep"));
        // The file path inside the CTE should remain as-is (part of the WITH clause)
        assert!(sql.contains("'raw.csv'"));
    }

    // ========================================================================
    // Query Method Tests: find_node()
    // ========================================================================

    #[test]
    fn test_find_node_basic() {
        let query = "SELECT x, y FROM data VISUALISE DRAW point MAPPING x AS x, y AS y";
        let tree = SourceTree::new(query).unwrap();
        let root = tree.root();

        // Find visualise_statement
        let viz_query = "(visualise_statement) @viz";
        let viz_node = tree.find_node(&root, viz_query);
        assert!(viz_node.is_some());
        assert_eq!(viz_node.unwrap().kind(), "visualise_statement");
    }

    #[test]
    fn test_find_node_returns_first_match() {
        let query = "SELECT x, y FROM data VISUALISE DRAW point DRAW line";
        let tree = SourceTree::new(query).unwrap();
        let root = tree.root();

        // Find draw_clause - should return first one
        let draw_query = "(draw_clause) @draw";
        let draw_node = tree.find_node(&root, draw_query);
        assert!(draw_node.is_some());

        // Verify it's the first draw clause by checking it contains "point"
        let text = tree.get_text(&draw_node.unwrap());
        assert!(text.contains("point"));
    }

    #[test]
    fn test_find_node_not_found() {
        let query = "SELECT x, y FROM data";
        let tree = SourceTree::new(query).unwrap();
        let root = tree.root();

        // Try to find visualise_statement in query without VISUALISE
        let viz_query = "(visualise_statement) @viz";
        let viz_node = tree.find_node(&root, viz_query);
        assert!(viz_node.is_none());
    }

    #[test]
    fn test_find_node_with_alternation() {
        let query = "SELECT x, y FROM data VISUALISE DRAW point";
        let tree = SourceTree::new(query).unwrap();
        let root = tree.root();

        // Use alternation pattern to match any identifier type (like in scale parsers)
        let ident_query = "[(identifier) (bare_identifier) (quoted_identifier)] @id";
        let ident_nodes = tree.find_nodes(&root, ident_query);

        // Should find multiple identifiers (x, y, data, point, etc.)
        assert!(!ident_nodes.is_empty());

        // Verify find_node returns the first one
        let first_ident = tree.find_node(&root, ident_query);
        assert!(first_ident.is_some());
    }

    // ========================================================================
    // Query Method Tests: find_nodes()
    // ========================================================================

    #[test]
    fn test_find_nodes_multiple_matches() {
        let query = "SELECT x, y FROM data VISUALISE DRAW point DRAW line DRAW bar";
        let tree = SourceTree::new(query).unwrap();
        let root = tree.root();

        // Find all draw_clause nodes
        let draw_query = "(draw_clause) @draw";
        let draw_nodes = tree.find_nodes(&root, draw_query);
        assert_eq!(draw_nodes.len(), 3);

        // Verify they contain the expected geoms
        let texts: Vec<String> = draw_nodes.iter().map(|n| tree.get_text(n)).collect();
        assert!(texts[0].contains("point"));
        assert!(texts[1].contains("line"));
        assert!(texts[2].contains("bar"));
    }

    #[test]
    fn test_find_nodes_empty() {
        let query = "SELECT x, y FROM data";
        let tree = SourceTree::new(query).unwrap();
        let root = tree.root();

        // Try to find draw_clause in query without VISUALISE
        let draw_query = "(draw_clause) @draw";
        let draw_nodes = tree.find_nodes(&root, draw_query);
        assert!(draw_nodes.is_empty());
    }

    #[test]
    fn test_find_nodes_with_alternation() {
        let query = "VISUALISE DRAW point MAPPING 'red' AS color, x AS x";
        let tree = SourceTree::new(query).unwrap();
        let root = tree.root();

        // Match both string and identifier nodes using alternation (like in TO clause parsing)
        let value_query = "[(string) (identifier)] @val";
        let value_nodes = tree.find_nodes(&root, value_query);

        // Should find multiple nodes
        assert!(
            !value_nodes.is_empty(),
            "Should find string and identifier nodes"
        );

        let texts: Vec<String> = value_nodes.iter().map(|n| tree.get_text(n)).collect();
        // Verify alternation pattern works - should find both string and identifier values
        assert!(
            texts.iter().any(|t| t.contains("red")),
            "Should find string 'red'"
        );
        assert!(texts.iter().any(|t| t == "x"), "Should find identifier x");
    }

    // ========================================================================
    // Query Method Tests: find_text() and find_texts()
    // ========================================================================

    #[test]
    fn test_find_text_basic() {
        let query = "SELECT x, y FROM data VISUALISE DRAW point";
        let tree = SourceTree::new(query).unwrap();
        let root = tree.root();

        // Find geom_type text
        let geom_query = "(geom_type) @geom";
        let geom_text = tree.find_text(&root, geom_query);
        assert_eq!(geom_text, Some("point".to_string()));
    }

    #[test]
    fn test_find_text_not_found() {
        let query = "SELECT x, y FROM data";
        let tree = SourceTree::new(query).unwrap();
        let root = tree.root();

        // Try to find geom_type in query without VISUALISE
        let geom_query = "(geom_type) @geom";
        let geom_text = tree.find_text(&root, geom_query);
        assert!(geom_text.is_none());
    }

    #[test]
    fn test_find_texts_multiple() {
        let query = "SELECT x, y FROM data VISUALISE DRAW point DRAW line DRAW bar";
        let tree = SourceTree::new(query).unwrap();
        let root = tree.root();

        // Find all geom_type texts
        let geom_query = "(geom_type) @geom";
        let geom_texts = tree.find_texts(&root, geom_query);
        assert_eq!(geom_texts.len(), 3);
        assert_eq!(geom_texts, vec!["point", "line", "bar"]);
    }

    #[test]
    fn test_find_texts_empty() {
        let query = "SELECT x, y FROM data";
        let tree = SourceTree::new(query).unwrap();
        let root = tree.root();

        // Try to find geom_type in query without VISUALISE
        let geom_query = "(geom_type) @geom";
        let geom_texts = tree.find_texts(&root, geom_query);
        assert!(geom_texts.is_empty());
    }

    #[test]
    fn test_find_texts_with_alternation() {
        let query = "SELECT col1, col2 FROM data";
        let tree = SourceTree::new(query).unwrap();
        let root = tree.root();

        // Match multiple identifier types (commonly used pattern in scale parsers)
        let ident_query = "[(identifier) (bare_identifier) (quoted_identifier)] @id";
        let ident_texts = tree.find_texts(&root, ident_query);

        // Should find identifiers: col1, col2, data
        assert!(ident_texts.len() >= 3);
        assert!(ident_texts.contains(&"col1".to_string()));
        assert!(ident_texts.contains(&"col2".to_string()));
        assert!(ident_texts.contains(&"data".to_string()));
    }

    // ========================================================================
    // Query Method Tests: get_text()
    // ========================================================================

    #[test]
    fn test_get_text_with_identifiers() {
        let query = "SELECT column_name FROM table_name";
        let tree = SourceTree::new(query).unwrap();
        let root = tree.root();

        // Find identifier nodes and extract text
        let ident_query = "(identifier) @id";
        let ident_texts = tree.find_texts(&root, ident_query);
        assert!(ident_texts.len() >= 2);
        assert!(ident_texts.contains(&"column_name".to_string()));
        assert!(ident_texts.contains(&"table_name".to_string()));
    }
}