Search in sources :

Example 6 with ParsingException

use of com.facebook.presto.sql.parser.ParsingException in project presto by prestodb.

the class HttpRequestSessionFactory method parsePreparedStatementsHeaders.

private static Map<String, String> parsePreparedStatementsHeaders(HttpServletRequest servletRequest) {
    Map<String, String> preparedStatements = new HashMap<>();
    for (String header : splitSessionHeader(servletRequest.getHeaders(PRESTO_PREPARED_STATEMENT))) {
        List<String> nameValue = Splitter.on('=').limit(2).trimResults().splitToList(header);
        assertRequest(nameValue.size() == 2, "Invalid %s header", PRESTO_PREPARED_STATEMENT);
        String statementName;
        String sqlString;
        try {
            statementName = urlDecode(nameValue.get(0));
            sqlString = urlDecode(nameValue.get(1));
        } catch (IllegalArgumentException e) {
            throw badRequest(format("Invalid %s header: %s", PRESTO_PREPARED_STATEMENT, e.getMessage()));
        }
        // Validate statement
        SqlParser sqlParser = new SqlParser();
        try {
            sqlParser.createStatement(sqlString);
        } catch (ParsingException e) {
            throw badRequest(format("Invalid %s header: %s", PRESTO_PREPARED_STATEMENT, e.getMessage()));
        }
        preparedStatements.put(statementName, sqlString);
    }
    return preparedStatements;
}
Also used : HashMap(java.util.HashMap) ParsingException(com.facebook.presto.sql.parser.ParsingException) SqlParser(com.facebook.presto.sql.parser.SqlParser)

Example 7 with ParsingException

use of com.facebook.presto.sql.parser.ParsingException in project presto by prestodb.

the class SqlQueryManager method createQuery.

@Override
public QueryInfo createQuery(SessionSupplier sessionSupplier, String query) {
    requireNonNull(sessionSupplier, "sessionFactory is null");
    requireNonNull(query, "query is null");
    checkArgument(!query.isEmpty(), "query must not be empty string");
    QueryId queryId = queryIdGenerator.createNextQueryId();
    Session session = null;
    QueryExecution queryExecution;
    Statement statement;
    try {
        session = sessionSupplier.createSession(queryId, transactionManager, accessControl, sessionPropertyManager);
        if (query.length() > maxQueryLength) {
            int queryLength = query.length();
            query = query.substring(0, maxQueryLength);
            throw new PrestoException(QUERY_TEXT_TOO_LARGE, format("Query text length (%s) exceeds the maximum length (%s)", queryLength, maxQueryLength));
        }
        Statement wrappedStatement = sqlParser.createStatement(query);
        statement = unwrapExecuteStatement(wrappedStatement, sqlParser, session);
        List<Expression> parameters = wrappedStatement instanceof Execute ? ((Execute) wrappedStatement).getParameters() : emptyList();
        validateParameters(statement, parameters);
        QueryExecutionFactory<?> queryExecutionFactory = executionFactories.get(statement.getClass());
        if (queryExecutionFactory == null) {
            throw new PrestoException(NOT_SUPPORTED, "Unsupported statement type: " + statement.getClass().getSimpleName());
        }
        if (statement instanceof Explain && ((Explain) statement).isAnalyze()) {
            Statement innerStatement = ((Explain) statement).getStatement();
            if (!(executionFactories.get(innerStatement.getClass()) instanceof SqlQueryExecutionFactory)) {
                throw new PrestoException(NOT_SUPPORTED, "EXPLAIN ANALYZE only supported for statements that are queries");
            }
        }
        queryExecution = queryExecutionFactory.createQueryExecution(queryId, query, session, statement, parameters);
    } catch (ParsingException | PrestoException | SemanticException e) {
        // This is intentionally not a method, since after the state change listener is registered
        // it's not safe to do any of this, and we had bugs before where people reused this code in a method
        URI self = locationFactory.createQueryLocation(queryId);
        // if session creation failed, create a minimal session object
        if (session == null) {
            session = Session.builder(new SessionPropertyManager()).setQueryId(queryId).setIdentity(sessionSupplier.getIdentity()).build();
        }
        Optional<ResourceGroupId> resourceGroup = Optional.empty();
        if (e instanceof QueryQueueFullException) {
            resourceGroup = Optional.of(((QueryQueueFullException) e).getResourceGroup());
        }
        QueryExecution execution = new FailedQueryExecution(queryId, query, resourceGroup, session, self, transactionManager, queryExecutor, metadata, e);
        QueryInfo queryInfo = null;
        try {
            queries.put(queryId, execution);
            queryInfo = execution.getQueryInfo();
            queryMonitor.queryCreatedEvent(queryInfo);
            queryMonitor.queryCompletedEvent(queryInfo);
            stats.queryFinished(queryInfo);
        } finally {
            // execution MUST be added to the expiration queue or there will be a leak
            expirationQueue.add(execution);
        }
        return queryInfo;
    }
    QueryInfo queryInfo = queryExecution.getQueryInfo();
    queryMonitor.queryCreatedEvent(queryInfo);
    queryExecution.addFinalQueryInfoListener(finalQueryInfo -> {
        try {
            QueryInfo info = queryExecution.getQueryInfo();
            stats.queryFinished(info);
            queryMonitor.queryCompletedEvent(info);
        } finally {
            expirationQueue.add(queryExecution);
        }
    });
    addStatsListener(queryExecution);
    queries.put(queryId, queryExecution);
    // start the query in the background
    queueManager.submit(statement, queryExecution, queryExecutor);
    return queryInfo;
}
Also used : Execute(com.facebook.presto.sql.tree.Execute) Optional(java.util.Optional) Statement(com.facebook.presto.sql.tree.Statement) QueryId(com.facebook.presto.spi.QueryId) Explain(com.facebook.presto.sql.tree.Explain) QueryQueueFullException(com.facebook.presto.execution.resourceGroups.QueryQueueFullException) PrestoException(com.facebook.presto.spi.PrestoException) URI(java.net.URI) SqlQueryExecutionFactory(com.facebook.presto.execution.SqlQueryExecution.SqlQueryExecutionFactory) Expression(com.facebook.presto.sql.tree.Expression) ParsingException(com.facebook.presto.sql.parser.ParsingException) SessionPropertyManager(com.facebook.presto.metadata.SessionPropertyManager) Session(com.facebook.presto.Session) SemanticException(com.facebook.presto.sql.analyzer.SemanticException)

Example 8 with ParsingException

use of com.facebook.presto.sql.parser.ParsingException in project presto by prestodb.

the class SqlFormatterUtil method getFormattedSql.

public static String getFormattedSql(Statement statement, SqlParser sqlParser, Optional<List<Expression>> parameters) {
    String sql = SqlFormatter.formatSql(statement, parameters);
    // verify round-trip
    Statement parsed;
    try {
        ParsingOptions parsingOptions = new ParsingOptions(REJECT);
        parsed = sqlParser.createStatement(sql, parsingOptions);
    } catch (ParsingException e) {
        throw new PrestoException(GENERIC_INTERNAL_ERROR, "Formatted query does not parse: " + statement);
    }
    if (!statement.equals(parsed)) {
        throw new PrestoException(GENERIC_INTERNAL_ERROR, "Query does not round-trip: " + statement);
    }
    return sql;
}
Also used : ParsingOptions(com.facebook.presto.sql.parser.ParsingOptions) Statement(com.facebook.presto.sql.tree.Statement) ParsingException(com.facebook.presto.sql.parser.ParsingException) PrestoException(com.facebook.presto.spi.PrestoException)

Example 9 with ParsingException

use of com.facebook.presto.sql.parser.ParsingException in project presto by prestodb.

the class DdlVerification method verify.

@Override
@SuppressWarnings("unchecked")
protected DdlMatchResult verify(QueryObjectBundle control, QueryObjectBundle test, Optional<QueryResult<Void>> controlQueryResult, Optional<QueryResult<Void>> testQueryResult, ChecksumQueryContext controlChecksumQueryContext, ChecksumQueryContext testChecksumQueryContext) {
    Statement controlChecksumQuery = getChecksumQuery(control);
    Statement testChecksumQuery = getChecksumQuery(test);
    controlChecksumQueryContext.setChecksumQuery(formatSql(controlChecksumQuery));
    testChecksumQueryContext.setChecksumQuery(formatSql(testChecksumQuery));
    String controlChecksum = getOnlyElement(callAndConsume(() -> getHelperAction().execute(controlChecksumQuery, CONTROL_CHECKSUM, checksumConverter), stats -> stats.getQueryStats().map(QueryStats::getQueryId).ifPresent(controlChecksumQueryContext::setChecksumQueryId)).getResults());
    String testChecksum = getOnlyElement(callAndConsume(() -> getHelperAction().execute(testChecksumQuery, TEST_CHECKSUM, checksumConverter), stats -> stats.getQueryStats().map(QueryStats::getQueryId).ifPresent(testChecksumQueryContext::setChecksumQueryId)).getResults());
    S controlObject;
    S testObject;
    try {
        controlObject = (S) sqlParser.createStatement(controlChecksum, PARSING_OPTIONS);
    } catch (ParsingException e) {
        return new DdlMatchResult(CONTROL_NOT_PARSABLE, Optional.of(e), controlChecksum, testChecksum);
    }
    try {
        testObject = (S) sqlParser.createStatement(testChecksum, PARSING_OPTIONS);
    } catch (ParsingException e) {
        return new DdlMatchResult(TEST_NOT_PARSABLE, Optional.of(e), controlChecksum, testChecksum);
    }
    return new DdlMatchResult(match(controlObject, testObject, control, test) ? MATCH : MISMATCH, Optional.empty(), controlChecksum, testChecksum);
}
Also used : PARSING_OPTIONS(com.facebook.presto.verifier.framework.VerifierUtil.PARSING_OPTIONS) QueryStats(com.facebook.presto.jdbc.QueryStats) Statement(com.facebook.presto.sql.tree.Statement) ParsingException(com.facebook.presto.sql.parser.ParsingException)

Aggregations

ParsingException (com.facebook.presto.sql.parser.ParsingException)9 Statement (com.facebook.presto.sql.tree.Statement)4 PrestoException (com.facebook.presto.spi.PrestoException)3 ParsingOptions (com.facebook.presto.sql.parser.ParsingOptions)2 SqlParser (com.facebook.presto.sql.parser.SqlParser)2 ImmutableList (com.google.common.collect.ImmutableList)2 IOException (java.io.IOException)2 URI (java.net.URI)2 JobState (com.airbnb.airpal.api.JobState)1 InvalidQueryException (com.airbnb.airpal.api.output.InvalidQueryException)1 FileTooLargeException (com.airbnb.airpal.api.output.builders.FileTooLargeException)1 JobOutputBuilder (com.airbnb.airpal.api.output.builders.JobOutputBuilder)1 Persistor (com.airbnb.airpal.api.output.persistors.Persistor)1 ExecutionFailureException (com.airbnb.airpal.core.execution.ExecutionClient.ExecutionFailureException)1 QueryTimeOutException (com.airbnb.airpal.core.execution.QueryClient.QueryTimeOutException)1 BasicQueryInfo (com.airbnb.airpal.presto.QueryInfoClient.BasicQueryInfo)1 Table (com.airbnb.airpal.presto.Table)1 Session (com.facebook.presto.Session)1 ErrorLocation (com.facebook.presto.client.ErrorLocation)1 QueryError (com.facebook.presto.client.QueryError)1