use of org.apache.asterix.lang.common.base.IParser in project asterixdb by apache.
the class ApiServlet method post.
@Override
protected void post(IServletRequest request, IServletResponse response) {
// Query language
ILangCompilationProvider compilationProvider = "AQL".equals(request.getParameter("query-language")) ? aqlCompilationProvider : sqlppCompilationProvider;
IParserFactory parserFactory = compilationProvider.getParserFactory();
// Output format.
PrintWriter out = response.writer();
OutputFormat format;
boolean csvAndHeader = false;
String output = request.getParameter("output-format");
try {
format = OutputFormat.valueOf(output);
} catch (IllegalArgumentException e) {
LOGGER.log(Level.INFO, output + ": unsupported output-format, using " + OutputFormat.CLEAN_JSON + " instead", e);
// Default output format
format = OutputFormat.CLEAN_JSON;
}
String query = request.getParameter("query");
String wrapperArray = request.getParameter("wrapper-array");
String printExprParam = request.getParameter("print-expr-tree");
String printRewrittenExprParam = request.getParameter("print-rewritten-expr-tree");
String printLogicalPlanParam = request.getParameter("print-logical-plan");
String printOptimizedLogicalPlanParam = request.getParameter("print-optimized-logical-plan");
String printJob = request.getParameter("print-job");
String executeQuery = request.getParameter("execute-query");
try {
response.setStatus(HttpResponseStatus.OK);
HttpUtil.setContentType(response, ContentType.TEXT_HTML, Encoding.UTF8);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failure setting content type", e);
response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
return;
}
try {
IHyracksClientConnection hcc = (IHyracksClientConnection) ctx.get(HYRACKS_CONNECTION_ATTR);
IHyracksDataset hds = (IHyracksDataset) ctx.get(HYRACKS_DATASET_ATTR);
if (hds == null) {
synchronized (ctx) {
hds = (IHyracksDataset) ctx.get(HYRACKS_DATASET_ATTR);
if (hds == null) {
hds = new HyracksDataset(hcc, appCtx.getCompilerProperties().getFrameSize(), ResultReader.NUM_READERS);
ctx.put(HYRACKS_DATASET_ATTR, hds);
}
}
}
IParser parser = parserFactory.createParser(query);
List<Statement> aqlStatements = parser.parse();
SessionConfig sessionConfig = new SessionConfig(format, true, isSet(executeQuery), true);
sessionConfig.set(SessionConfig.FORMAT_HTML, true);
sessionConfig.set(SessionConfig.FORMAT_CSV_HEADER, csvAndHeader);
sessionConfig.set(SessionConfig.FORMAT_WRAPPER_ARRAY, isSet(wrapperArray));
sessionConfig.setOOBData(isSet(printExprParam), isSet(printRewrittenExprParam), isSet(printLogicalPlanParam), isSet(printOptimizedLogicalPlanParam), isSet(printJob));
SessionOutput sessionOutput = new SessionOutput(sessionConfig, out);
MetadataManager.INSTANCE.init();
IStatementExecutor translator = statementExectorFactory.create(appCtx, aqlStatements, sessionOutput, compilationProvider, componentProvider);
double duration;
long startTime = System.currentTimeMillis();
translator.compileAndExecute(hcc, hds, IStatementExecutor.ResultDelivery.IMMEDIATE, null, new IStatementExecutor.Stats());
long endTime = System.currentTimeMillis();
duration = (endTime - startTime) / 1000.00;
out.println(HTML_STATEMENT_SEPARATOR);
out.println("<PRE>Duration of all jobs: " + duration + " sec</PRE>");
} catch (AsterixException | TokenMgrError | org.apache.asterix.aqlplus.parser.TokenMgrError pe) {
GlobalConfig.ASTERIX_LOGGER.log(Level.INFO, pe.toString(), pe);
ResultUtil.webUIParseExceptionHandler(out, pe, query);
} catch (Exception e) {
GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, e.getMessage(), e);
ResultUtil.webUIErrorHandler(out, e);
}
}
use of org.apache.asterix.lang.common.base.IParser in project asterixdb by apache.
the class ExecuteStatementRequestMessage method handle.
@Override
public void handle(ICcApplicationContext ccAppCtx) throws HyracksDataException, InterruptedException {
ICCServiceContext ccSrvContext = ccAppCtx.getServiceContext();
ClusterControllerService ccSrv = (ClusterControllerService) ccSrvContext.getControllerService();
CCApplication ccApp = (CCApplication) ccSrv.getApplication();
CCMessageBroker messageBroker = (CCMessageBroker) ccSrvContext.getMessageBroker();
CCExtensionManager ccExtMgr = (CCExtensionManager) ccAppCtx.getExtensionManager();
ILangCompilationProvider compilationProvider = ccExtMgr.getCompilationProvider(lang);
IStorageComponentProvider storageComponentProvider = ccAppCtx.getStorageComponentProvider();
IStatementExecutorFactory statementExecutorFactory = ccApp.getStatementExecutorFactory();
IStatementExecutorContext statementExecutorContext = ccApp.getStatementExecutorContext();
ccSrv.getExecutor().submit(() -> {
ExecuteStatementResponseMessage responseMsg = new ExecuteStatementResponseMessage(requestMessageId);
try {
final IClusterManagementWork.ClusterState clusterState = ClusterStateManager.INSTANCE.getState();
if (clusterState != IClusterManagementWork.ClusterState.ACTIVE) {
throw new IllegalStateException("Cannot execute request, cluster is " + clusterState);
}
IParser parser = compilationProvider.getParserFactory().createParser(statementsText);
List<Statement> statements = parser.parse();
StringWriter outWriter = new StringWriter(256);
PrintWriter outPrinter = new PrintWriter(outWriter);
SessionOutput.ResultDecorator resultPrefix = ResultUtil.createPreResultDecorator();
SessionOutput.ResultDecorator resultPostfix = ResultUtil.createPostResultDecorator();
SessionOutput.ResultAppender appendHandle = ResultUtil.createResultHandleAppender(handleUrl);
SessionOutput.ResultAppender appendStatus = ResultUtil.createResultStatusAppender();
SessionOutput sessionOutput = new SessionOutput(sessionConfig, outPrinter, resultPrefix, resultPostfix, appendHandle, appendStatus);
IStatementExecutor.ResultMetadata outMetadata = new IStatementExecutor.ResultMetadata();
MetadataManager.INSTANCE.init();
IStatementExecutor translator = statementExecutorFactory.create(ccAppCtx, statements, sessionOutput, compilationProvider, storageComponentProvider);
translator.compileAndExecute(ccAppCtx.getHcc(), null, delivery, outMetadata, new IStatementExecutor.Stats(), clientContextID, statementExecutorContext);
outPrinter.close();
responseMsg.setResult(outWriter.toString());
responseMsg.setMetadata(outMetadata);
} catch (AlgebricksException | HyracksException | TokenMgrError | org.apache.asterix.aqlplus.parser.TokenMgrError pe) {
// we trust that "our" exceptions are serializable and have a comprehensible error message
GlobalConfig.ASTERIX_LOGGER.log(Level.WARNING, pe.getMessage(), pe);
responseMsg.setError(pe);
} catch (Exception e) {
GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, "Unexpected exception", e);
responseMsg.setError(new Exception(e.toString()));
}
try {
messageBroker.sendApplicationMessageToNC(responseMsg, requestNodeId);
} catch (Exception e) {
LOGGER.log(Level.WARNING, e.toString(), e);
}
});
}
use of org.apache.asterix.lang.common.base.IParser in project asterixdb by apache.
the class AQLTestCase method testAQL.
@Test
public void testAQL() throws UnsupportedEncodingException, FileNotFoundException, ParseException, AsterixException, AlgebricksException {
Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(queryFile), "UTF-8"));
IParser parser = aqlParserFactory.createParser(reader);
GlobalConfig.ASTERIX_LOGGER.info(queryFile.toString());
try {
parser.parse();
} catch (Exception e) {
GlobalConfig.ASTERIX_LOGGER.warning("Failed while testing file " + reader);
StringWriter sw = new StringWriter();
PrintWriter writer = new PrintWriter(sw);
e.printStackTrace(writer);
GlobalConfig.ASTERIX_LOGGER.warning(sw.toString());
throw new ParseException("Parsing " + queryFile.toString());
}
}
use of org.apache.asterix.lang.common.base.IParser in project asterixdb by apache.
the class AQLToSQLPPConverter method convert.
private static void convert(File src, File dest) throws Exception {
if (src.isFile()) {
BufferedReader parserReader = new BufferedReader(new InputStreamReader(new FileInputStream(src)));
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(src)));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest)));
try {
String line = null;
while ((line = reader.readLine()) != null) {
if (line.startsWith("/*") || line.startsWith(" *") || line.startsWith("*") || line.startsWith("\t") || line.startsWith(" \t")) {
writer.write(line + "\n");
} else {
break;
}
}
writer.write("\n");
reader.close();
IParser parser = aqlParserFactory.createParser(parserReader);
List<Statement> statements = parser.parse();
parserReader.close();
String sqlString = AQLFormatPrintUtil.toSQLPPString(statements);
writer.write(sqlString);
} catch (Exception e) {
System.out.println("AQL parser fails at: " + src.getAbsolutePath());
//e.printStackTrace();
} finally {
parserReader.close();
reader.close();
writer.close();
}
BufferedReader sqlReader = new BufferedReader(new InputStreamReader(new FileInputStream(dest)));
try {
IParser sqlParser = sqlppParserFactory.createParser(sqlReader);
sqlParser.parse();
} catch (Exception e) {
System.out.println("SQL++ parser cannot parse: ");
System.out.println(dest.getAbsolutePath());
e.printStackTrace();
} finally {
sqlReader.close();
}
return;
}
for (File child : src.listFiles()) {
String lastName = child.getName();
lastName = lastName.replaceAll("\\.aql", "\\.sqlpp");
File targetChild = new File(dest, lastName);
if (child.isDirectory()) {
FileUtils.forceMkdir(targetChild);
} else {
targetChild.createNewFile();
}
convert(child, targetChild);
}
}
use of org.apache.asterix.lang.common.base.IParser in project asterixdb by apache.
the class ParserTestExecutor method testSQLPPParser.
// Tests the SQL++ parser.
public void testSQLPPParser(File queryFile, File actualResultFile, File expectedFile) throws Exception {
actualResultFile.getParentFile().mkdirs();
PrintWriter writer = new PrintWriter(new FileOutputStream(actualResultFile));
IParser parser = sqlppParserFactory.createParser(readTestFile(queryFile));
GlobalConfig.ASTERIX_LOGGER.info(queryFile.toString());
try {
List<Statement> statements = parser.parse();
List<FunctionDecl> functions = getDeclaredFunctions(statements);
String dvName = getDefaultDataverse(statements);
MetadataProvider metadataProvider = mock(MetadataProvider.class);
@SuppressWarnings("unchecked") Map<String, String> config = mock(Map.class);
when(metadataProvider.getDefaultDataverseName()).thenReturn(dvName);
when(metadataProvider.getConfig()).thenReturn(config);
when(config.get(FunctionUtil.IMPORT_PRIVATE_FUNCTIONS)).thenReturn("true");
when(metadataProvider.findDataset(anyString(), anyString())).thenReturn(mock(Dataset.class));
for (Statement st : statements) {
if (st.getKind() == Statement.Kind.QUERY) {
Query query = (Query) st;
IQueryRewriter rewriter = sqlppRewriterFactory.createQueryRewriter();
rewrite(rewriter, functions, query, metadataProvider, new LangRewritingContext(query.getVarCounter()));
// Tests deep copy and deep equality.
Query copiedQuery = (Query) SqlppRewriteUtil.deepCopy(query);
Assert.assertEquals(query.hashCode(), copiedQuery.hashCode());
Assert.assertEquals(query, copiedQuery);
}
SqlppAstPrintUtil.print(st, writer);
}
writer.close();
// Compares the actual result and the expected result.
runScriptAndCompareWithResult(queryFile, new PrintWriter(System.err), expectedFile, actualResultFile, ComparisonEnum.TEXT);
} catch (Exception e) {
GlobalConfig.ASTERIX_LOGGER.warning("Failed while testing file " + queryFile);
throw e;
} finally {
writer.close();
}
}
Aggregations