Search in sources :

Example 6 with H2PooledConnection

use of org.apache.ignite.internal.processors.query.h2.H2PooledConnection in project ignite by apache.

the class SchemaManager method createTable.

/**
 * Create db table by using given table descriptor.
 *
 * @param schemaName Schema name.
 * @param schema Schema.
 * @param tbl Table descriptor.
 * @param conn Connection.
 * @throws SQLException If failed to create db table.
 * @throws IgniteCheckedException If failed.
 */
private GridH2Table createTable(String schemaName, H2Schema schema, H2TableDescriptor tbl, H2PooledConnection conn) throws SQLException, IgniteCheckedException {
    assert schema != null;
    assert tbl != null;
    String sql = H2Utils.tableCreateSql(tbl);
    if (log.isDebugEnabled())
        log.debug("Creating DB table with SQL: " + sql);
    GridH2RowDescriptor rowDesc = new GridH2RowDescriptor(tbl, tbl.type());
    GridH2Table h2Tbl = H2TableEngine.createTable(conn.connection(), sql, rowDesc, tbl, ctx.indexProcessor());
    for (GridH2IndexBase usrIdx : tbl.createUserIndexes()) createInitialUserIndex(schemaName, tbl, usrIdx);
    return h2Tbl;
}
Also used : GridH2IndexBase(org.apache.ignite.internal.processors.query.h2.opt.GridH2IndexBase) GridH2RowDescriptor(org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)

Example 7 with H2PooledConnection

use of org.apache.ignite.internal.processors.query.h2.H2PooledConnection in project ignite by apache.

the class UpdatePlanBuilder method checkPlanCanBeDistributed.

/**
 * Checks whether the given update plan can be distributed and returns additional info.
 *
 * @param idx Indexing.
 * @param mvccEnabled Mvcc flag.
 * @param planKey Plan key.
 * @param selectQry Derived select query.
 * @param cacheName Cache name.
 * @return distributed update plan info, or {@code null} if cannot be distributed.
 * @throws IgniteCheckedException if failed.
 */
private static DmlDistributedPlanInfo checkPlanCanBeDistributed(IgniteH2Indexing idx, boolean mvccEnabled, QueryDescriptor planKey, String selectQry, String cacheName, IgniteLogger log) throws IgniteCheckedException {
    if ((!mvccEnabled && !planKey.skipReducerOnUpdate()) || planKey.batched())
        return null;
    try (H2PooledConnection conn = idx.connections().connection(planKey.schemaName())) {
        H2Utils.setupConnection(conn, QueryContext.parseContext(idx.backupFilter(null, null), planKey.local()), planKey.distributedJoins(), planKey.enforceJoinOrder());
        // Get a new prepared statement for derived select query.
        try (PreparedStatement stmt = conn.prepareStatement(selectQry, H2StatementCache.queryFlags(planKey))) {
            Prepared prep = GridSqlQueryParser.prepared(stmt);
            GridSqlQuery selectStmt = (GridSqlQuery) new GridSqlQueryParser(false, log).parse(prep);
            GridCacheTwoStepQuery qry = GridSqlQuerySplitter.split(conn, selectStmt, selectQry, planKey.collocated(), planKey.distributedJoins(), planKey.enforceJoinOrder(), false, idx, prep.getParameters().size(), log);
            boolean distributed = // No split for local
            !qry.isLocalSplit() && // Over real caches
            qry.hasCacheIds() && // No merge table
            qry.skipMergeTable() && qry.mapQueries().size() == 1 && // One w/o subqueries
            !qry.mapQueries().get(0).hasSubQueries();
            if (distributed) {
                List<Integer> cacheIds = H2Utils.collectCacheIds(idx, CU.cacheId(cacheName), qry.tables());
                H2Utils.checkQuery(idx, cacheIds, qry.tables());
                return new DmlDistributedPlanInfo(qry.isReplicatedOnly(), cacheIds, qry.derivedPartitions());
            } else
                return null;
        }
    } catch (SQLException e) {
        throw new IgniteCheckedException(e);
    }
}
Also used : GridSqlQuery(org.apache.ignite.internal.processors.query.h2.sql.GridSqlQuery) H2PooledConnection(org.apache.ignite.internal.processors.query.h2.H2PooledConnection) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) SQLException(java.sql.SQLException) IgniteSQLException(org.apache.ignite.internal.processors.query.IgniteSQLException) GridSqlQueryParser(org.apache.ignite.internal.processors.query.h2.sql.GridSqlQueryParser) Prepared(org.h2.command.Prepared) GridCacheTwoStepQuery(org.apache.ignite.internal.processors.cache.query.GridCacheTwoStepQuery) PreparedStatement(java.sql.PreparedStatement)

Example 8 with H2PooledConnection

use of org.apache.ignite.internal.processors.query.h2.H2PooledConnection in project ignite by apache.

the class GridQueryParsingTest method parse.

/**
 * @param sql Sql.
 */
@SuppressWarnings("unchecked")
private <T extends Prepared> T parse(String sql) throws Exception {
    try (H2PooledConnection conn = connection()) {
        Session ses = H2Utils.session(conn);
        H2Utils.setupConnection(conn, QueryContext.parseContext(null, true), false, false, false);
        return (T) ses.prepare(sql);
    }
}
Also used : H2PooledConnection(org.apache.ignite.internal.processors.query.h2.H2PooledConnection) Session(org.h2.engine.Session)

Example 9 with H2PooledConnection

use of org.apache.ignite.internal.processors.query.h2.H2PooledConnection 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 10 with H2PooledConnection

use of org.apache.ignite.internal.processors.query.h2.H2PooledConnection in project ignite by apache.

the class H2Utils method setupConnection.

/**
 * @param conn Connection to use.
 * @param qctx Query context.
 * @param distributedJoins If distributed joins are enabled.
 * @param enforceJoinOrder Enforce join order of tables.
 * @param lazy Lazy query execution mode.
 */
public static void setupConnection(H2PooledConnection conn, QueryContext qctx, boolean distributedJoins, boolean enforceJoinOrder, boolean lazy) {
    Session s = session(conn);
    s.setForceJoinOrder(enforceJoinOrder);
    s.setJoinBatchEnabled(distributedJoins);
    s.setLazyQueryExecution(lazy);
    QueryContext oldCtx = (QueryContext) s.getVariable(QCTX_VARIABLE_NAME).getObject();
    assert oldCtx == null || oldCtx == qctx : oldCtx;
    s.setVariable(QCTX_VARIABLE_NAME, new ValueRuntimeSimpleObject<>(qctx));
    // Hack with thread local context is used only for H2 methods that is called without Session object.
    // e.g. GridH2Table.getRowCountApproximation (used only on optimization phase, after parse).
    QueryContext.threadLocal(qctx);
}
Also used : QueryContext(org.apache.ignite.internal.processors.query.h2.opt.QueryContext) Session(org.h2.engine.Session)

Aggregations

SQLException (java.sql.SQLException)7 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)7 PreparedStatement (java.sql.PreparedStatement)6 QueryContext (org.apache.ignite.internal.processors.query.h2.opt.QueryContext)6 QueryCancelledException (org.apache.ignite.cache.query.QueryCancelledException)5 H2PooledConnection (org.apache.ignite.internal.processors.query.h2.H2PooledConnection)5 ResultSet (java.sql.ResultSet)4 ArrayList (java.util.ArrayList)4 Collections.singletonList (java.util.Collections.singletonList)4 List (java.util.List)4 CacheException (javax.cache.CacheException)4 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)4 Session (org.h2.engine.Session)4 IgniteClientDisconnectedException (org.apache.ignite.IgniteClientDisconnectedException)3 IgniteException (org.apache.ignite.IgniteException)3 QueryRetryException (org.apache.ignite.cache.query.QueryRetryException)3 GridCacheSqlQuery (org.apache.ignite.internal.processors.cache.query.GridCacheSqlQuery)3 GridCacheTwoStepQuery (org.apache.ignite.internal.processors.cache.query.GridCacheTwoStepQuery)3 TraceSurroundings (org.apache.ignite.internal.processors.tracing.MTC.TraceSurroundings)3 IgniteTxAlreadyCompletedCheckedException (org.apache.ignite.internal.transactions.IgniteTxAlreadyCompletedCheckedException)3