@@ -17,6 +17,72 @@ pub use cst::SyntaxNode;
17
17
pub use cst:: SyntaxToken ;
18
18
use lexer:: parser_error:: ParserError ;
19
19
20
+ /// "Parse SQL and construct a Complete Syntax Tree (CST) to return.
21
+ ///
22
+ /// # Examples
23
+ ///
24
+ /// ```
25
+ /// use postgresql_cst_parser::{parse, syntax_kind::SyntaxKind};
26
+ ///
27
+ /// fn main() {
28
+ /// // Parse SQL query and get the syntax tree
29
+ /// let sql = "SELECT tbl.a as a, tbl.b from TBL tbl WHERE tbl.a > 0;";
30
+ /// let root = parse(sql).unwrap();
31
+ ///
32
+ /// // Example 1: Extract all column references from the query
33
+ /// let column_refs: Vec<String> = root
34
+ /// .descendants()
35
+ /// .filter(|node| node.kind() == SyntaxKind::columnref)
36
+ /// .map(|node| node.text().to_string())
37
+ /// .collect();
38
+ ///
39
+ /// println!("Column references: {:?}", column_refs); // ["tbl.a", "tbl.b", "tbl.a"]
40
+ ///
41
+ /// // Example 2: Find the WHERE condition
42
+ /// if let Some(where_clause) = root
43
+ /// .descendants()
44
+ /// .find(|node| node.kind() == SyntaxKind::where_clause)
45
+ /// {
46
+ /// println!("WHERE condition: {}", where_clause.text());
47
+ /// }
48
+ ///
49
+ /// // Example 3: Get the selected table name
50
+ /// if let Some(relation_expr) = root
51
+ /// .descendants()
52
+ /// .find(|node| node.kind() == SyntaxKind::relation_expr)
53
+ /// {
54
+ /// if let Some(name_node) = relation_expr
55
+ /// .descendants()
56
+ /// .find(|node| node.kind() == SyntaxKind::ColId)
57
+ /// {
58
+ /// println!("Table name: {}", name_node.text());
59
+ /// }
60
+ /// }
61
+ ///
62
+ /// // Example 4: Parse complex SQL and extract specific nodes
63
+ /// let complex_sql = "WITH data AS (SELECT id, value FROM source WHERE value > 10)
64
+ /// SELECT d.id, d.value, COUNT(*) OVER (PARTITION BY d.id)
65
+ /// FROM data d JOIN other o ON d.id = o.id
66
+ /// ORDER BY d.value DESC LIMIT 10;";
67
+ ///
68
+ /// let complex_root = parse(complex_sql).unwrap();
69
+ ///
70
+ /// // Extract CTEs (Common Table Expressions)
71
+ /// let ctes: Vec<_> = complex_root
72
+ /// .descendants()
73
+ /// .filter(|node| node.kind() == SyntaxKind::common_table_expr)
74
+ /// .collect();
75
+ ///
76
+ /// // Extract window functions
77
+ /// let window_funcs: Vec<_> = complex_root
78
+ /// .descendants()
79
+ /// .filter(|node| node.kind() == SyntaxKind::over_clause)
80
+ /// .collect();
81
+ ///
82
+ /// println!("Number of CTEs: {}", ctes.len());
83
+ /// println!("Number of window functions: {}", window_funcs.len());
84
+ /// }
85
+ /// ```
20
86
pub fn parse ( input : & str ) -> Result < ResolvedNode , ParserError > {
21
87
cst:: parse ( input)
22
88
}
0 commit comments