Search in sources :

Example 1 with JdbcParameterMeta

use of org.apache.ignite.internal.processors.odbc.jdbc.JdbcParameterMeta in project ignite by apache.

the class OdbcRequestHandler method getParamsMeta.

/**
 * {@link OdbcQueryGetQueryMetaRequest} command handler.
 * Returns metadata for the parameters to be set.
 *
 * @param req Get params metadata request.
 * @return Response.
 */
private ClientListenerResponse getParamsMeta(OdbcQueryGetParamsMetaRequest req) {
    try {
        String sql = OdbcEscapeUtils.parse(req.query());
        String schema = OdbcUtils.prepareSchema(req.schema());
        SqlFieldsQueryEx qry = makeQuery(schema, sql);
        List<JdbcParameterMeta> params = ctx.query().getIndexing().parameterMetaData(schema, qry);
        byte[] typeIds = new byte[params.size()];
        for (int i = 0; i < params.size(); ++i) {
            int sqlType = params.get(i).type();
            typeIds[i] = sqlTypeToBinary(sqlType);
        }
        OdbcQueryGetParamsMetaResult res = new OdbcQueryGetParamsMetaResult(typeIds);
        return new OdbcResponse(res);
    } catch (Exception e) {
        U.error(log, "Failed to get params metadata [reqId=" + req.requestId() + ", req=" + req + ']', e);
        return exceptionToResult(e);
    }
}
Also used : JdbcParameterMeta(org.apache.ignite.internal.processors.odbc.jdbc.JdbcParameterMeta) SqlFieldsQueryEx(org.apache.ignite.internal.processors.cache.query.SqlFieldsQueryEx) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) BatchUpdateException(java.sql.BatchUpdateException) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException)

Example 2 with JdbcParameterMeta

use of org.apache.ignite.internal.processors.odbc.jdbc.JdbcParameterMeta in project ignite by apache.

the class JdbcPreparedStatement method parameterMetaData.

/**
 * Fetches parameters metadata of the specified query.
 */
private ParameterMetaData parameterMetaData() throws SQLException {
    SqlFieldsQueryEx qry = new SqlFieldsQueryEx(sql, null);
    setupQuery(qry);
    try {
        List<JdbcParameterMeta> params = conn.ignite().context().query().getIndexing().parameterMetaData(conn.schemaName(), qry);
        return new JdbcThinParameterMetadata(params);
    } catch (IgniteSQLException ex) {
        throw ex.toJdbcException();
    }
}
Also used : JdbcParameterMeta(org.apache.ignite.internal.processors.odbc.jdbc.JdbcParameterMeta) SqlFieldsQueryEx(org.apache.ignite.internal.processors.cache.query.SqlFieldsQueryEx) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) JdbcThinParameterMetadata(org.apache.ignite.internal.jdbc.thin.JdbcThinParameterMetadata)

Example 3 with JdbcParameterMeta

use of org.apache.ignite.internal.processors.odbc.jdbc.JdbcParameterMeta in project ignite by apache.

the class QueryParser method parseH2.

/**
 * Parse and split query if needed, cache either two-step query or statement.
 *
 * @param schemaName Schema name.
 * @param qry Query.
 * @param batched Batched flag.
 * @param remainingAllowed Whether multiple statements are allowed.
 * @return Parsing result.
 */
@SuppressWarnings("IfMayBeConditional")
private QueryParserResult parseH2(String schemaName, SqlFieldsQuery qry, boolean batched, boolean remainingAllowed) {
    try (H2PooledConnection c = connMgr.connection(schemaName)) {
        // For queries that are explicitly local, we rely on the flag specified in the query
        // because this parsing result will be cached and used for queries directly.
        // For other queries, we enforce join order at this stage to avoid premature optimizations
        // (and therefore longer parsing) as long as there'll be more parsing at split stage.
        boolean enforceJoinOrderOnParsing = (!qry.isLocal() || qry.isEnforceJoinOrder());
        QueryContext qctx = QueryContext.parseContext(idx.backupFilter(null, null), qry.isLocal());
        H2Utils.setupConnection(c, qctx, false, enforceJoinOrderOnParsing, false);
        PreparedStatement stmt = null;
        try {
            stmt = c.prepareStatementNoCache(qry.getSql());
            if (qry.isLocal() && GridSqlQueryParser.checkMultipleStatements(stmt))
                throw new IgniteSQLException("Multiple statements queries are not supported for local queries.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
            GridSqlQueryParser.PreparedWithRemaining prep = GridSqlQueryParser.preparedWithRemaining(stmt);
            Prepared prepared = prep.prepared();
            if (GridSqlQueryParser.isExplainUpdate(prepared))
                throw new IgniteSQLException("Explains of update queries are not supported.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
            // Get remaining query and check if it is allowed.
            SqlFieldsQuery remainingQry = null;
            if (!F.isEmpty(prep.remainingSql())) {
                checkRemainingAllowed(remainingAllowed);
                remainingQry = cloneFieldsQuery(qry).setSql(prep.remainingSql());
            }
            // Prepare new query.
            SqlFieldsQuery newQry = cloneFieldsQuery(qry).setSql(prepared.getSQL());
            final int paramsCnt = prepared.getParameters().size();
            Object[] argsOrig = qry.getArgs();
            Object[] args = null;
            Object[] remainingArgs = null;
            if (!batched && paramsCnt > 0) {
                if (argsOrig == null || argsOrig.length < paramsCnt)
                    // Not enough parameters, but we will handle this later on execution phase.
                    args = argsOrig;
                else {
                    args = Arrays.copyOfRange(argsOrig, 0, paramsCnt);
                    if (paramsCnt != argsOrig.length)
                        remainingArgs = Arrays.copyOfRange(argsOrig, paramsCnt, argsOrig.length);
                }
            } else
                remainingArgs = argsOrig;
            newQry.setArgs(args);
            QueryDescriptor newQryDesc = queryDescriptor(schemaName, newQry);
            if (remainingQry != null)
                remainingQry.setArgs(remainingArgs);
            final List<JdbcParameterMeta> paramsMeta;
            try {
                paramsMeta = H2Utils.parametersMeta(stmt.getParameterMetaData());
                assert prepared.getParameters().size() == paramsMeta.size();
            } catch (IgniteCheckedException | SQLException e) {
                throw new IgniteSQLException("Failed to get parameters metadata", IgniteQueryErrorCode.UNKNOWN, e);
            }
            // Do actual parsing.
            if (CommandProcessor.isCommand(prepared)) {
                GridSqlStatement cmdH2 = new GridSqlQueryParser(false, log).parse(prepared);
                QueryParserResultCommand cmd = new QueryParserResultCommand(null, cmdH2, false);
                return new QueryParserResult(newQryDesc, queryParameters(newQry), remainingQry, paramsMeta, null, null, cmd);
            } else if (CommandProcessor.isCommandNoOp(prepared)) {
                QueryParserResultCommand cmd = new QueryParserResultCommand(null, null, true);
                return new QueryParserResult(newQryDesc, queryParameters(newQry), remainingQry, paramsMeta, null, null, cmd);
            } else if (GridSqlQueryParser.isDml(prepared)) {
                QueryParserResultDml dml = prepareDmlStatement(newQryDesc, prepared);
                return new QueryParserResult(newQryDesc, queryParameters(newQry), remainingQry, paramsMeta, null, dml, null);
            } else if (!prepared.isQuery()) {
                throw new IgniteSQLException("Unsupported statement: " + newQry.getSql(), IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
            }
            // Parse SELECT.
            GridSqlQueryParser parser = new GridSqlQueryParser(false, log);
            GridSqlQuery selectStmt = (GridSqlQuery) parser.parse(prepared);
            List<Integer> cacheIds = parser.cacheIds();
            Integer mvccCacheId = mvccCacheIdForSelect(parser.objectsMap());
            // Calculate if query is in fact can be executed locally.
            boolean loc = qry.isLocal();
            if (!loc) {
                if (parser.isLocalQuery())
                    loc = true;
            }
            // If this is a local query, check if it must be split.
            boolean locSplit = false;
            if (loc) {
                GridCacheContext cctx = parser.getFirstPartitionedCache();
                if (cctx != null && cctx.config().getQueryParallelism() > 1)
                    locSplit = true;
            }
            // Split is required either if query is distributed, or when it is local, but executed
            // over segmented PARTITIONED case. In this case multiple map queries will be executed against local
            // node stripes in parallel and then merged through reduce process.
            boolean splitNeeded = !loc || locSplit;
            String forUpdateQryOutTx = null;
            String forUpdateQryTx = null;
            GridCacheTwoStepQuery forUpdateTwoStepQry = null;
            boolean forUpdate = GridSqlQueryParser.isForUpdateQuery(prepared);
            // column to be able to lock selected rows further.
            if (forUpdate) {
                // We have checked above that it's not an UNION query, so it's got to be SELECT.
                assert selectStmt instanceof GridSqlSelect;
                // Check FOR UPDATE invariants: only one table, MVCC is there.
                if (cacheIds.size() != 1)
                    throw new IgniteSQLException("SELECT FOR UPDATE is supported only for queries " + "that involve single transactional cache.");
                if (mvccCacheId == null)
                    throw new IgniteSQLException("SELECT FOR UPDATE query requires transactional cache " + "with MVCC enabled.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION);
                // We need a copy because we are going to modify AST a bit. We do not want to modify original select.
                GridSqlSelect selForUpdate = ((GridSqlSelect) selectStmt).copySelectForUpdate();
                // Clear forUpdate flag to run it as a plain query.
                selForUpdate.forUpdate(false);
                ((GridSqlSelect) selectStmt).forUpdate(false);
                // Remember sql string without FOR UPDATE clause.
                forUpdateQryOutTx = selForUpdate.getSQL();
                GridSqlAlias keyCol = keyColumn(selForUpdate);
                selForUpdate.addColumn(keyCol, true);
                // Remember sql string without FOR UPDATE clause and with _key column.
                forUpdateQryTx = selForUpdate.getSQL();
                // Prepare additional two-step query for FOR UPDATE case.
                if (splitNeeded) {
                    c.schema(newQry.getSchema());
                    forUpdateTwoStepQry = GridSqlQuerySplitter.split(c, selForUpdate, forUpdateQryTx, newQry.isCollocated(), newQry.isDistributedJoins(), newQry.isEnforceJoinOrder(), locSplit, idx, paramsCnt, log);
                }
            }
            GridCacheTwoStepQuery twoStepQry = null;
            if (splitNeeded) {
                GridSubqueryJoinOptimizer.pullOutSubQueries(selectStmt);
                c.schema(newQry.getSchema());
                twoStepQry = GridSqlQuerySplitter.split(c, selectStmt, newQry.getSql(), newQry.isCollocated(), newQry.isDistributedJoins(), newQry.isEnforceJoinOrder(), locSplit, idx, paramsCnt, log);
            }
            List<GridQueryFieldMetadata> meta = H2Utils.meta(stmt.getMetaData());
            QueryParserResultSelect select = new QueryParserResultSelect(selectStmt, twoStepQry, forUpdateTwoStepQry, meta, cacheIds, mvccCacheId, forUpdateQryOutTx, forUpdateQryTx);
            return new QueryParserResult(newQryDesc, queryParameters(newQry), remainingQry, paramsMeta, select, null, null);
        } catch (IgniteCheckedException | SQLException e) {
            throw new IgniteSQLException("Failed to parse query. " + e.getMessage(), IgniteQueryErrorCode.PARSING, e);
        } finally {
            U.close(stmt, log);
        }
    }
}
Also used : GridSqlAlias(org.apache.ignite.internal.processors.query.h2.sql.GridSqlAlias) SQLException(java.sql.SQLException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) GridSqlStatement(org.apache.ignite.internal.processors.query.h2.sql.GridSqlStatement) Prepared(org.h2.command.Prepared) GridCacheTwoStepQuery(org.apache.ignite.internal.processors.cache.query.GridCacheTwoStepQuery) GridQueryFieldMetadata(org.apache.ignite.internal.processors.query.GridQueryFieldMetadata) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridCacheContext(org.apache.ignite.internal.processors.cache.GridCacheContext) JdbcParameterMeta(org.apache.ignite.internal.processors.odbc.jdbc.JdbcParameterMeta) PreparedStatement(java.sql.PreparedStatement) QueryContext(org.apache.ignite.internal.processors.query.h2.opt.QueryContext) GridSqlSelect(org.apache.ignite.internal.processors.query.h2.sql.GridSqlSelect) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) GridSqlQuery(org.apache.ignite.internal.processors.query.h2.sql.GridSqlQuery) GridSqlQueryParser(org.apache.ignite.internal.processors.query.h2.sql.GridSqlQueryParser) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException)

Example 4 with JdbcParameterMeta

use of org.apache.ignite.internal.processors.odbc.jdbc.JdbcParameterMeta in project ignite by apache.

the class IgniteH2Indexing method parameterMetaData.

/**
 * {@inheritDoc}
 */
@Override
public List<JdbcParameterMeta> parameterMetaData(String schemaName, SqlFieldsQuery qry) throws IgniteSQLException {
    assert qry != null;
    ArrayList<JdbcParameterMeta> metas = new ArrayList<>();
    SqlFieldsQuery curQry = qry;
    while (curQry != null) {
        QueryParserResult parsed = parser.parse(schemaName, curQry, true);
        metas.addAll(parsed.parametersMeta());
        curQry = parsed.remainingQuery();
    }
    return metas;
}
Also used : JdbcParameterMeta(org.apache.ignite.internal.processors.odbc.jdbc.JdbcParameterMeta) ArrayList(java.util.ArrayList) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery)

Example 5 with JdbcParameterMeta

use of org.apache.ignite.internal.processors.odbc.jdbc.JdbcParameterMeta in project ignite by apache.

the class H2Utils method parametersMeta.

/**
 * Converts h2 parameters metadata to Ignite one.
 *
 * @param h2ParamsMeta parameters metadata returned by h2.
 * @return Descriptions of the parameters.
 */
public static List<JdbcParameterMeta> parametersMeta(ParameterMetaData h2ParamsMeta) throws IgniteCheckedException {
    try {
        int paramsSize = h2ParamsMeta.getParameterCount();
        if (paramsSize == 0)
            return Collections.emptyList();
        ArrayList<JdbcParameterMeta> params = new ArrayList<>(paramsSize);
        for (int i = 1; i <= paramsSize; i++) params.add(new JdbcParameterMeta(h2ParamsMeta, i));
        return params;
    } catch (SQLException e) {
        throw new IgniteCheckedException("Failed to get parameters metadata", e);
    }
}
Also used : IgniteCheckedException(org.apache.ignite.IgniteCheckedException) JdbcParameterMeta(org.apache.ignite.internal.processors.odbc.jdbc.JdbcParameterMeta) SQLException(java.sql.SQLException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) ArrayList(java.util.ArrayList)

Aggregations

JdbcParameterMeta (org.apache.ignite.internal.processors.odbc.jdbc.JdbcParameterMeta)5 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)4 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)3 SQLException (java.sql.SQLException)2 ArrayList (java.util.ArrayList)2 SqlFieldsQuery (org.apache.ignite.cache.query.SqlFieldsQuery)2 SqlFieldsQueryEx (org.apache.ignite.internal.processors.cache.query.SqlFieldsQueryEx)2 BatchUpdateException (java.sql.BatchUpdateException)1 PreparedStatement (java.sql.PreparedStatement)1 IgniteException (org.apache.ignite.IgniteException)1 IgniteInterruptedCheckedException (org.apache.ignite.internal.IgniteInterruptedCheckedException)1 JdbcThinParameterMetadata (org.apache.ignite.internal.jdbc.thin.JdbcThinParameterMetadata)1 GridCacheContext (org.apache.ignite.internal.processors.cache.GridCacheContext)1 GridCacheTwoStepQuery (org.apache.ignite.internal.processors.cache.query.GridCacheTwoStepQuery)1 GridQueryFieldMetadata (org.apache.ignite.internal.processors.query.GridQueryFieldMetadata)1 QueryContext (org.apache.ignite.internal.processors.query.h2.opt.QueryContext)1 GridSqlAlias (org.apache.ignite.internal.processors.query.h2.sql.GridSqlAlias)1 GridSqlQuery (org.apache.ignite.internal.processors.query.h2.sql.GridSqlQuery)1 GridSqlQueryParser (org.apache.ignite.internal.processors.query.h2.sql.GridSqlQueryParser)1 GridSqlSelect (org.apache.ignite.internal.processors.query.h2.sql.GridSqlSelect)1