我正在使用foundationDB SQL解析器(https://github.com/FoundationDB/sql-parser)来解析Java内部的查询,但我对解析器使用的访问者设计模式不是很熟悉使用查询。
我想像这样向解析器发送一个查询:“SELECT a, b FROM c WHERE d > 5”并得到结果:
- SELECT子句中的所有字段名称(已完成)
- 将表名放入FROM子句(已完成)
- WHERE子句中的列名、操作数和表达式
这就是我正在实现的代码:
@Override
public QueryDescription parse() throws StandardException {
SQLParser parser = new SQLParser();
StatementNode stmt = parser.parseStatement(sql);
Visitor v = new Visitor() {
@Override
public boolean visitChildrenFirst(Visitable arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public Visitable visit(Visitable arg0) throws StandardException {
// Temporary stores the QueryDescription parameters
StatementEnum se = null;
String fromTable = null;
String[] fields = null;
if(arg0 instanceof CursorNode) {
CursorNode cn = (CursorNode) arg0;
// print out what statement is been declared in sql query
System.out.println("Statement: " + cn.statementToString());
// temporarly stores the statement
String statement = cn.statementToString();
// creates the right StatementEnum
if(statement == "CREATE TABLE") {
se = StatementEnum.CREATE_TABLE;
} else if(statement == "INSERT") {
se = StatementEnum.INSERT;
} else if(statement == "SELECT") {
se = StatementEnum.SELECT;
} else if(statement == "DROP TABLE") {
se = StatementEnum.DROP_TABLE;
}
}
description = new QueryDescription(se, fromTable, fields);
return arg0;
}
@Override
public boolean stopTraversal() { return false; }
@Override
public boolean skipChildren(Visitable arg0) throws StandardException { return false; }
};
stmt.accept(v);
// TODO remove, only for debug purpose
stmt.treePrint();
return description;
}
这就是 QueryDescription 类代码:
public class QueryDescription {
/* Member variables: */
private QueryTypeEnum queryType;
private StatementEnum statement;
private String fromTable;
private String[] fields;
/* Constructors: */
/**
*
* @param statement
* @param fromTable
* @param fields
*/
public QueryDescription(StatementEnum statement, String fromTable, String[] fields) {
this.statement = statement;
this.fromTable = fromTable;
this.fields = fields;
}
/* Methods: */
/**
* Analyze which type of query is the one passed by parameter and assigns the right queryTypeEnum
*/
public void assignType() {
switch(statement) {
case CREATE_TABLE:
break;
case SELECT:
if(fields[0] == "allFields")
queryType = QueryTypeEnum.DUMP;
else {
// TODO risolvere questione del WHERE
queryType = QueryTypeEnum.SELECT_FROM;
}
break;
case UPDATE:
break;
case INSERT:
break;
case DROP_TABLE:
break;
}
}
/* Getters and Setter: */
/**
*
* @return the queryType
*/
public QueryTypeEnum getQueryType() {
return queryType;
}
/**
*
* @return the statement
*/
public StatementEnum getStatement() {
return statement;
}
/**
*
* @return the from table
*/
public String getFromTable() {
return fromTable;
}
/**
*
* @return the fields
*/
public String[] getFields() {
return fields;
}
}