It can generate an AST of the query from a string. The AST nodes implement the Visitor Pattern so you can easily work with it.
gem install rgviz
Ruby on Rails
There is a separate project on top of this library called rgviz-rails, check it out!
First you must require the library:
require 'rubygems' require 'rgviz'
To parse a query:
query = Rgviz::Parser.parse 'select name where age > 20'
Read the source code for the AST nodes, it's not very big and the nodes just map to the query structure.
If you pass :extensions => true to the parse method these new scalar functions will be available:
concat: converts each of its arguments to a string and then concatenates them. For example: concat(1, '-', '2') returns '1-2'. Can also receive just a single argument to convert it to a string.
So to have this function parsed you need to do:
query = Rgviz::Parser.parse 'select concat(name, age)', :extensions => true
These new functions are not part of Google's query language, but they are very handy so we added them. These functions are also supported by rgviz-rails.
Using the Visitor Pattern
class MyVisitor < Rgviz::Visitor def visit_select(node) # do something with the node puts 'before select' puts node.columns.length # returning true means visiting this node children true end def end_visit_select(node) # This will be invoked after visiting the node puts "after select" end def visit_id_column(node) puts node.name end end query = Rgviz::Parser.parse 'select name, age' query.accept MyVisitor.new # outputs: # before select # 2 # name # age # after select
There is a visit_XXX and end_visit_XXX for every node in the language.
Wrappers for Google DataTable and others
You can use Rgviz::HtmlRenderer.render(table) and Rgviz::CsvRenderer.render(table) to get a string to render in html or csv output format.