SQL expression parse tree traversal in preorder/inorder/postorder
SQL expression(condition) was often used in where clause to filter which records are returned in the query’s result set. Manipulate expression is a very common task when you process SQL query in your program. This demo illustrate how to iterate expression to list atomic elements in pre-order, in-order and post-order. Here is another example if you want to modify expression.
Expression in where clause of this SQL will be iterated.
SELECT f1 FROM t1 WHERE t1.a = 10.2 AND name = 'k' OR id IN ( 2, 4, 5 )
SQL expression parse tree traversal in pre-order
OR AND = t1.a 10.2 = name 'k' IN id () , 2 , 4 5
SQL expression parse tree traversal in in-order
t1.a = 10.2 AND name = 'k' OR id IN 2 , 4 , 5 ()
SQL expression parse tree traversal in post-order
t1.a 10.2 = name 'k' = AND id 2 4 5 , , () IN OR
Demo code in C#
using System; using System.Collections.Generic; using System.Text; using gudusoft.gsqlparser; using gudusoft.gsqlparser.Units; namespace visitexpression { class visitexpression { static void Main(string[] args) { TGSqlParser sqlparser = new TGSqlParser(TDbVendor.DbVOracle); sqlparser.SqlText.Text = @"SELECT f1 FROM t1 WHERE t1.a = 10.2 AND name = 'k' OR id IN ( 2, 4, 5 ) HAVING MAX(x) > 6 "; Console.WriteLine("Processing.."); int i = sqlparser.Parse(); if (i == 0) { visitbinaryexprtree(sqlparser.SqlStatements[0].WhereClause); } else Console.WriteLine(sqlparser.ErrorMessages); } public static void visitbinaryexprtree(TLzCustomExpression pExpr) { Console.WriteLine("pre-order:"); pExpr.PreOrderTraverse(treenodevisitor); Console.WriteLine("in-order:"); pExpr.InOrderTraverse(treenodevisitor); Console.WriteLine("post-order:"); pExpr.PostOrderTraverse(treenodevisitor); } public static Boolean treenodevisitor(TLz_Node pnode, Boolean pIsLeafNode) { TLzCustomExpression lcexpr; if (pIsLeafNode) { Console.WriteLine(pnode.AsText); } else { lcexpr = (TLzCustomExpression)pnode; if (lcexpr.oper == TLzOpType.Expr_Parenthesis) { Console.WriteLine("()"); } else if (lcexpr.opname != null) { Console.WriteLine(lcexpr.opname.AsText); } } return true; } } }
Download this demo: C# version, Java version