-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathsource_tree.rs
More file actions
589 lines (487 loc) · 21.2 KB
/
Copy pathsource_tree.rs
File metadata and controls
589 lines (487 loc) · 21.2 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
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
//! 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::validate::validate_sql_safety;
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()))?;
Ok(Self {
tree,
source,
language,
})
}
/// 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) with safety validation.
///
/// If VISUALISE FROM is used, this injects "SELECT * FROM <source>"
/// Returns None if there's no SQL portion and no VISUALISE FROM injection needed.
///
/// Returns an error if the SQL contains dangerous operations (DROP, DELETE, etc.)
pub fn extract_sql(&self) -> Result<Option<String>> {
let sql = self.extract_sql_unchecked();
if let Some(ref sql_text) = sql {
validate_sql_safety(sql_text)?;
}
Ok(sql)
}
/// Extract the SQL portion without safety validation.
///
/// Use this only in trusted environments or when validation is handled separately.
/// Prefer `extract_sql()` for user-provided queries.
pub fn extract_sql_unchecked(&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_text = self
.find_node(&root, "(sql_portion) @sql")
.map(|node| self.get_text(&node))
.unwrap_or_default();
// Check if any VISUALISE statement has FROM clause
let from_query = r#"
(visualise_statement
(from_clause
(table_ref) @table))
"#;
if let Some(from_identifier) = self.find_text(&root, from_query) {
// Inject SELECT * FROM <source>
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 {
// No injection needed - return SQL if not empty
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().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().unwrap();
assert_eq!(sql, "SELECT * FROM data");
let viz = tree.extract_visualise().unwrap();
assert!(viz.starts_with("visualise"));
}
#[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().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().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_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().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() {
// CREATE is blocked by safety validation, use unchecked for this test
let query = "CREATE TABLE x AS SELECT 1; VISUALISE FROM x";
let tree = SourceTree::new(query).unwrap();
let sql = tree.extract_sql_unchecked().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_unchecked().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() {
// INSERT is blocked by safety validation, use unchecked for this test
let query = "INSERT INTO x VALUES (1) VISUALISE FROM x DRAW";
let tree = SourceTree::new(query).unwrap();
let sql = tree.extract_sql_unchecked().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().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
}
#[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().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().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().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'"));
}
// ========================================================================
// SQL Safety Validation Tests
// ========================================================================
#[test]
fn test_extract_sql_blocks_delete() {
// DELETE is supported by grammar, so validation should block it
let query = "DELETE FROM users VISUALISE DRAW point";
let tree = SourceTree::new(query).unwrap();
let result = tree.extract_sql();
assert!(result.is_err(), "Expected error, got: {:?}", result);
assert!(result.unwrap_err().to_string().contains("DELETE"));
}
#[test]
fn test_extract_sql_blocks_update() {
// UPDATE is supported by grammar, so validation should block it
let query = "UPDATE users SET name = 'foo' VISUALISE DRAW point";
let tree = SourceTree::new(query).unwrap();
let result = tree.extract_sql();
assert!(result.is_err(), "Expected error, got: {:?}", result);
assert!(result.unwrap_err().to_string().contains("UPDATE"));
}
#[test]
fn test_extract_sql_allows_keyword_in_string() {
let query = "SELECT 'DELETE' as x FROM data VISUALISE DRAW point";
let tree = SourceTree::new(query).unwrap();
let result = tree.extract_sql();
assert!(result.is_ok(), "Should allow DELETE in string literal");
}
// ========================================================================
// 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()));
}
}