com.googlecode.mjorm.mql.StatementImpl Maven / Gradle / Ivy
package com.googlecode.mjorm.mql;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.tree.Tree;
import com.googlecode.mjorm.ObjectIterator;
import com.googlecode.mjorm.ObjectMapper;
import com.mongodb.DB;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
public class StatementImpl
implements Statement {
private static final Logger LOGGER = Logger.getLogger(StatementImpl.class.getName());
private Tree tree;
private Map parameters;
private Interpreter interpreter;
private ObjectMapper objectMapper;
/**
* Creates the {@link StatementImpl}
* @param mql {@link InputStream} that contains MQL code
* @param db the mongo {@link DB}
* @param objectMapper the {@link ObjectMapper}
* @throws IOException on error
* @throws RecognitionException on error
*/
public StatementImpl(InputStream mql, DB db, ObjectMapper objectMapper)
throws IOException, RecognitionException {
try {
this.interpreter = InterpreterFactory.getDefaultInstance().create(db, objectMapper);
this.tree = interpreter.compile(mql);
} catch(Exception e) {
throw new MqlException(e);
}
this.parameters = new HashMap();
this.objectMapper = objectMapper;
}
/**
* {@inheritDoc}
*/
public Statement setParameters(Map params) {
parameters.clear();
parameters.putAll(params);
return this;
}
/**
* {@inheritDoc}
*/
public Statement setParameters(Object... params) {
parameters.clear();
for (int i=0; i ObjectIterator execute(Class clazz) {
return new ObjectIterator(execute(), objectMapper, clazz);
}
/**
* {@inheritDoc}
*/
public T executeSingle(Class clazz) {
return objectMapper.map(executeSingle(), clazz);
}
/**
* {@inheritDoc}
*/
public void executeUpdate() {
executeInternal();
}
/**
* Executes the statement and returns the very
* last {@link InterpreterResult}.
* @return
*/
private InterpreterResult executeInternal() {
List res = interpreter.interpret(tree, parameters);
if (res.isEmpty()) {
throw new MqlException("No InterpreterResult was returned");
} else if (res.size()>1) {
LOGGER.warning(
"interpretation returned more than one "
+"InterpreterResult, using the last");
}
return res.get(res.size()-1);
}
}