mardi 3 mars 2015

Injectable, Poppable Stack


Background


A project involves converting a relational expression map (rxm) to an XML/SQL statement. The map resembles:



root > people, # "root" keyword starts the document
person > person, # maps table context to a node
.first_name > first, # maps a column to a node
.last_name > name/last, # maps a column to an ancestor node
.age > @age, # @ maps a column to an attribute node
account.person_id +> person.person_id, # +> performs an INNER JOIN
account > account, # context is now "account" node
.id > @id, # account id attribute
^, # pop stack to previous context
address > address, # switch context to "address" node
.*, # .* globs all columns
account.person_id -> company.person_id, # -> performs an OUTER JOIN
; # Starts the optional WHERE clause


The rxm is converted into Java classes using ANTLR.


Walking through the AST uses a Visitor pattern that calls methods for entering and exiting various parts of the tree. For example:



@Override
public void enterRoot( QueryParser.RootContext context ) {
System.out.println( "Root: " + context.getChild(2).getText() );
}

@Override
public void exitRoot( QueryParser.RootContext context ) {
System.out.println( "<< root" );
}


Problem


The code needs to generate an XML/SQL statement along the lines of:



XMLROOT (
XMLELEMENT (
NAME people,
XMLELEMENT (
NAME person,
XMLATTRIBUTE( ... )
)
),
VERSION ’1.0’,
STANDALONE YES
)


At the time that either enterRoot or exitRoot are called, it is not known whether there will be another line mapped using rxm. Ideally, I'd like to write:



@Override
public void enterRoot( QueryParser.RootContext context ) {
String root = context.getChild(2).getText();
getStack().push( "SELECT XMLROOT( XMLELEMENT( NAME " + root );
getStack().push( "VERSION '1.0', STANDALONE YES )" );
}


Question


Using a stack seems to be a good way to generate the query based on the visitor pattern.


What data structure would you use to convert a linear map into a hierarchical query?


Would it be feasible, for example, to just pop the last element from the stack (i.e., the line containing the closing parenthesis), store it locally, then push it back on afterwards?





Aucun commentaire:

Enregistrer un commentaire