Search in sources :

Example 71 with AND

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.AND in project ignite by apache.

the class IgniteH2Indexing method executeSelectLocal.

/**
 * Queries individual fields (generally used by JDBC drivers).
 *
 * @param qryId Query id.
 * @param qryDesc Query descriptor.
 * @param qryParams Query parameters.
 * @param select Select.
 * @param filter Cache name and key filter.
 * @param mvccTracker Query tracker.
 * @param cancel Query cancel.
 * @param inTx Flag whether the query is executed in transaction.
 * @param timeout Timeout.
 * @return Query result.
 * @throws IgniteCheckedException If failed.
 */
private GridQueryFieldsResult executeSelectLocal(long qryId, QueryDescriptor qryDesc, QueryParameters qryParams, QueryParserResultSelect select, final IndexingQueryFilter filter, MvccQueryTracker mvccTracker, GridQueryCancel cancel, boolean inTx, int timeout) throws IgniteCheckedException {
    assert !select.mvccEnabled() || mvccTracker != null;
    String qry;
    if (select.forUpdate())
        qry = inTx ? select.forUpdateQueryTx() : select.forUpdateQueryOutTx();
    else
        qry = qryDesc.sql();
    boolean mvccEnabled = mvccTracker != null;
    try {
        assert select != null;
        if (ctx.security().enabled())
            checkSecurity(select.cacheIds());
        MvccSnapshot mvccSnapshot = null;
        if (mvccEnabled)
            mvccSnapshot = mvccTracker.snapshot();
        final QueryContext qctx = new QueryContext(0, filter, null, mvccSnapshot, null, true);
        return new GridQueryFieldsResultAdapter(select.meta(), null) {

            @Override
            public GridCloseableIterator<List<?>> iterator() throws IgniteCheckedException {
                H2PooledConnection conn = connections().connection(qryDesc.schemaName());
                try (TraceSurroundings ignored = MTC.support(ctx.tracing().create(SQL_ITER_OPEN, MTC.span()))) {
                    H2Utils.setupConnection(conn, qctx, qryDesc.distributedJoins(), qryDesc.enforceJoinOrder(), qryParams.lazy());
                    PreparedStatement stmt = conn.prepareStatement(qry, H2StatementCache.queryFlags(qryDesc));
                    // Convert parameters into BinaryObjects.
                    Marshaller m = ctx.config().getMarshaller();
                    byte[] paramsBytes = U.marshal(m, qryParams.arguments());
                    final ClassLoader ldr = U.resolveClassLoader(ctx.config());
                    Object[] params;
                    if (m instanceof BinaryMarshaller) {
                        params = BinaryUtils.rawArrayFromBinary(((BinaryMarshaller) m).binaryMarshaller().unmarshal(paramsBytes, ldr));
                    } else
                        params = U.unmarshal(m, paramsBytes, ldr);
                    H2Utils.bindParameters(stmt, F.asList(params));
                    H2QueryInfo qryInfo = new H2QueryInfo(H2QueryInfo.QueryType.LOCAL, stmt, qry, ctx.localNodeId(), qryId);
                    ResultSet rs = executeSqlQueryWithTimer(stmt, conn, qry, timeout, cancel, qryParams.dataPageScanEnabled(), qryInfo);
                    return new H2FieldsIterator(rs, mvccTracker, conn, qryParams.pageSize(), log, IgniteH2Indexing.this, qryInfo, ctx.tracing());
                } catch (IgniteCheckedException | RuntimeException | Error e) {
                    conn.close();
                    try {
                        if (mvccTracker != null)
                            mvccTracker.onDone();
                    } catch (Exception e0) {
                        e.addSuppressed(e0);
                    }
                    throw e;
                }
            }
        };
    } catch (Exception e) {
        GridNearTxLocal tx = null;
        if (mvccEnabled && (tx != null || (tx = tx(ctx)) != null))
            tx.setRollbackOnly();
        throw e;
    }
}
Also used : MvccSnapshot(org.apache.ignite.internal.processors.cache.mvcc.MvccSnapshot) Marshaller(org.apache.ignite.marshaller.Marshaller) BinaryMarshaller(org.apache.ignite.internal.binary.BinaryMarshaller) GridQueryFieldsResultAdapter(org.apache.ignite.internal.processors.query.GridQueryFieldsResultAdapter) BinaryMarshaller(org.apache.ignite.internal.binary.BinaryMarshaller) GridNearTxLocal(org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal) PreparedStatement(java.sql.PreparedStatement) H2Utils.generateFieldsQueryString(org.apache.ignite.internal.processors.query.h2.H2Utils.generateFieldsQueryString) QueryContext(org.apache.ignite.internal.processors.query.h2.opt.QueryContext) TraceSurroundings(org.apache.ignite.internal.processors.tracing.MTC.TraceSurroundings) QueryCancelledException(org.apache.ignite.cache.query.QueryCancelledException) BatchUpdateException(java.sql.BatchUpdateException) ClusterTopologyServerNotFoundException(org.apache.ignite.internal.cluster.ClusterTopologyServerNotFoundException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteClusterReadOnlyException(org.apache.ignite.internal.processors.cache.distributed.dht.IgniteClusterReadOnlyException) CacheServerNotFoundException(org.apache.ignite.cache.CacheServerNotFoundException) SQLException(java.sql.SQLException) IgniteException(org.apache.ignite.IgniteException) CacheException(javax.cache.CacheException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) ResultSet(java.sql.ResultSet) Collections.singletonList(java.util.Collections.singletonList) ArrayList(java.util.ArrayList) List(java.util.List) KeyCacheObject(org.apache.ignite.internal.processors.cache.KeyCacheObject)

Example 72 with AND

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.AND in project ignite by apache.

the class PartitionExtractor method extractFromIn.

/**
 * Extract partition information from IN.
 *
 * @param op Operation.
 * @param tblModel Table model.
 * @return Partition.
 */
private PartitionNode extractFromIn(GridSqlOperation op, PartitionTableModel tblModel) throws IgniteCheckedException {
    // Operation should contain at least two children: left (column) and right (const or column).
    if (op.size() < 2)
        return PartitionAllNode.INSTANCE;
    // Left operand should be column.
    GridSqlAst left = op.child();
    GridSqlColumn leftCol = unwrapColumn(left);
    if (leftCol == null)
        return PartitionAllNode.INSTANCE;
    // Can work only with Ignite tables.
    if (!(leftCol.column().getTable() instanceof GridH2Table))
        return PartitionAllNode.INSTANCE;
    Set<PartitionSingleNode> parts = new HashSet<>();
    for (int i = 1; i < op.size(); i++) {
        GridSqlAst right = op.child(i);
        GridSqlConst rightConst;
        GridSqlParameter rightParam;
        if (right instanceof GridSqlConst) {
            rightConst = (GridSqlConst) right;
            rightParam = null;
        } else if (right instanceof GridSqlParameter) {
            rightConst = null;
            rightParam = (GridSqlParameter) right;
        } else
            // set globally. Hence, returning null.
            return PartitionAllNode.INSTANCE;
        // Extract.
        PartitionSingleNode part = extractSingle(leftCol, rightConst, rightParam, tblModel);
        // Same thing as above: single unknown partition in disjunction defeats optimization.
        if (part == null)
            return PartitionAllNode.INSTANCE;
        parts.add(part);
    }
    return parts.size() == 1 ? parts.iterator().next() : new PartitionGroupNode(parts);
}
Also used : GridSqlConst(org.apache.ignite.internal.processors.query.h2.sql.GridSqlConst) GridSqlAst(org.apache.ignite.internal.processors.query.h2.sql.GridSqlAst) GridSqlColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) PartitionSingleNode(org.apache.ignite.internal.sql.optimizer.affinity.PartitionSingleNode) GridSqlParameter(org.apache.ignite.internal.processors.query.h2.sql.GridSqlParameter) PartitionGroupNode(org.apache.ignite.internal.sql.optimizer.affinity.PartitionGroupNode) HashSet(java.util.HashSet)

Example 73 with AND

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.AND in project ignite by apache.

the class GridSubqueryJoinOptimizer method buildConditionBush.

/**
 * Creates tree from provided elements which will be connected with an AND operator.
 *
 * @param ops Ops.
 * @return Root of the resulting tree.
 */
private static GridSqlElement buildConditionBush(List<GridSqlElement> ops) {
    assert !F.isEmpty(ops);
    if (ops.size() == 1)
        return ops.get(0);
    int m = (ops.size() + 1) / 2;
    GridSqlElement left = buildConditionBush(ops.subList(0, m));
    GridSqlElement right = buildConditionBush(ops.subList(m, ops.size()));
    return new GridSqlOperation(AND, left, right);
}
Also used : GridSqlElement(org.apache.ignite.internal.processors.query.h2.sql.GridSqlElement) GridSqlOperation(org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperation)

Example 74 with AND

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.AND in project ignite by apache.

the class GridSubqueryJoinOptimizer method pullOutSubQryFromTableList.

/**
 * Pull out sub-select from table list.
 * <p>
 * Example:
 * <pre>
 *   Before:
 *     SELECT d.name
 *       FROM emp e,
 *            (select * from dep) d
 *      WHERE e.dep_id = d.id
 *        AND e.sal > 2000
 *
 *   After:
 *     SELECT d.name
 *       FROM emp e
 *       JOIN dep d
 *      WHERE sal > 2000 AND d.id = e.dep_id
 * </pre>
 *
 * @param parent Parent select.
 * @param target Target sql element. Can be {@code null}.
 * @param childInd Column index.
 */
private static boolean pullOutSubQryFromTableList(GridSqlSelect parent, @Nullable GridSqlAst target, int childInd) {
    if (target != null && !ELEMENT_IS_JOIN.test(target))
        return false;
    GridSqlAlias wrappedSubQry = target != null ? target.child(childInd) : (GridSqlAlias) parent.from();
    GridSqlSubquery subQry = GridSqlAlias.unwrap(wrappedSubQry);
    if (!isSimpleSelect(subQry.subquery()))
        return false;
    GridSqlSelect subSel = subQry.subquery();
    if (!(subSel.from() instanceof GridSqlAlias) && !(subSel.from() instanceof GridSqlTable))
        // we can't deal with joins and others right now
        return false;
    GridSqlAlias subTbl = new GridSqlAlias(wrappedSubQry.alias(), GridSqlAlias.unwrap(subSel.from()));
    if (target == null)
        // it's true only when the subquery is only table in the table list
        // so we can safely replace entire FROM expression of the parent
        parent.from(subTbl);
    else
        target.child(childInd, subTbl);
    GridSqlAst where = subSel.where();
    if (where != null) {
        if (target != null) {
            GridSqlJoin join = (GridSqlJoin) target;
            join.child(GridSqlJoin.ON_CHILD, new GridSqlOperation(AND, join.on(), where));
        } else
            parent.where(parent.where() == null ? where : new GridSqlOperation(AND, parent.where(), where));
    }
    remapColumns(parent, subSel, // reference equality used intentionally here
    col -> wrappedSubQry == col.expressionInFrom(), subTbl);
    return true;
}
Also used : GridSqlAlias(org.apache.ignite.internal.processors.query.h2.sql.GridSqlAlias) GridSqlSubquery(org.apache.ignite.internal.processors.query.h2.sql.GridSqlSubquery) GridSqlAst(org.apache.ignite.internal.processors.query.h2.sql.GridSqlAst) GridSqlJoin(org.apache.ignite.internal.processors.query.h2.sql.GridSqlJoin) GridSqlTable(org.apache.ignite.internal.processors.query.h2.sql.GridSqlTable) GridSqlOperation(org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperation) GridSqlSelect(org.apache.ignite.internal.processors.query.h2.sql.GridSqlSelect)

Example 75 with AND

use of org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.AND in project ignite by apache.

the class GridSubqueryJoinOptimizer method pullOutSubQueries.

/**
 * Pulls out subquery from parent query where possible.
 *
 * @param parent Parent query where to find and pull out subqueries.
 */
public static void pullOutSubQueries(GridSqlQuery parent) {
    if (!optimizationEnabled())
        return;
    if (parent instanceof GridSqlUnion) {
        GridSqlUnion union = (GridSqlUnion) parent;
        pullOutSubQueries(union.left());
        pullOutSubQueries(union.right());
        return;
    }
    assert parent instanceof GridSqlSelect : "\"parent\" should be instance of GridSqlSelect class";
    GridSqlSelect select = (GridSqlSelect) parent;
    pullOutSubQryFromSelectExpr(select);
    pullOutSubQryFromInClause(select);
    pullOutSubQryFromExistsClause(select);
    pullOutSubQryFromTableList(select);
}
Also used : GridSqlUnion(org.apache.ignite.internal.processors.query.h2.sql.GridSqlUnion) GridSqlSelect(org.apache.ignite.internal.processors.query.h2.sql.GridSqlSelect)

Aggregations

IgniteCheckedException (org.apache.ignite.IgniteCheckedException)37 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)33 ArrayList (java.util.ArrayList)26 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)25 List (java.util.List)22 IgniteException (org.apache.ignite.IgniteException)21 SQLException (java.sql.SQLException)15 GridCacheContext (org.apache.ignite.internal.processors.cache.GridCacheContext)15 GridH2RowDescriptor (org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor)13 HashMap (java.util.HashMap)12 Column (org.h2.table.Column)12 LinkedHashMap (java.util.LinkedHashMap)11 GridQueryTypeDescriptor (org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor)11 Index (org.h2.index.Index)11 PreparedStatement (java.sql.PreparedStatement)9 SqlFieldsQuery (org.apache.ignite.cache.query.SqlFieldsQuery)9 GridQueryProperty (org.apache.ignite.internal.processors.query.GridQueryProperty)9 UpdatePlan (org.apache.ignite.internal.processors.query.h2.dml.UpdatePlan)9 GridSqlColumn (org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn)9 GridSqlElement (org.apache.ignite.internal.processors.query.h2.sql.GridSqlElement)9