Search in sources :

Example 6 with JdbcResultSet

use of org.h2.jdbc.JdbcResultSet in project h2database by h2database.

the class JdbcConnection method getGeneratedKeys.

/**
 * INTERNAL
 */
ResultSet getGeneratedKeys(JdbcStatement stat, int id) {
    getGeneratedKeys = prepareCommand("SELECT SCOPE_IDENTITY() " + "WHERE SCOPE_IDENTITY() IS NOT NULL", getGeneratedKeys);
    ResultInterface result = getGeneratedKeys.executeQuery(0, false);
    return new JdbcResultSet(this, stat, getGeneratedKeys, result, id, false, true, false);
}
Also used : ResultInterface(org.h2.result.ResultInterface)

Example 7 with JdbcResultSet

use of org.h2.jdbc.JdbcResultSet in project ignite by apache.

the class GridMapQueryExecutor method onQueryRequest0.

/**
 * @param node Node authored request.
 * @param qryId Query ID.
 * @param reqId Request ID.
 * @param segmentId index segment ID.
 * @param schemaName Schema name.
 * @param qrys Queries to execute.
 * @param cacheIds Caches which will be affected by these queries.
 * @param topVer Topology version.
 * @param partsMap Partitions map for unstable topology.
 * @param parts Explicit partitions for current node.
 * @param pageSize Page size.
 * @param distributedJoins Query distributed join mode.
 * @param enforceJoinOrder Enforce join order H2 flag.
 * @param replicated Replicated only flag.
 * @param timeout Query timeout.
 * @param params Query parameters.
 * @param lazy Streaming flag.
 * @param mvccSnapshot MVCC snapshot.
 * @param dataPageScanEnabled If data page scan is enabled.
 */
private void onQueryRequest0(final ClusterNode node, final long qryId, final long reqId, final int segmentId, final String schemaName, final Collection<GridCacheSqlQuery> qrys, final List<Integer> cacheIds, final AffinityTopologyVersion topVer, final Map<UUID, int[]> partsMap, final int[] parts, final int pageSize, final boolean distributedJoins, final boolean enforceJoinOrder, final boolean replicated, final int timeout, final Object[] params, boolean lazy, @Nullable final MvccSnapshot mvccSnapshot, Boolean dataPageScanEnabled, boolean treatReplicatedAsPartitioned) {
    boolean performanceStatsEnabled = ctx.performanceStatistics().enabled();
    if (performanceStatsEnabled)
        IoStatisticsQueryHelper.startGatheringQueryStatistics();
    // Prepare to run queries.
    GridCacheContext<?, ?> mainCctx = mainCacheContext(cacheIds);
    MapNodeResults nodeRess = resultsForNode(node.id());
    MapQueryResults qryResults = null;
    PartitionReservation reserved = null;
    QueryContext qctx = null;
    // We don't use try with resources on purpose - the catch block must also be executed in the context of this span.
    TraceSurroundings trace = MTC.support(ctx.tracing().create(SQL_QRY_EXEC_REQ, MTC.span()).addTag(SQL_QRY_TEXT, () -> qrys.stream().map(GridCacheSqlQuery::query).collect(Collectors.joining("; "))));
    try {
        if (topVer != null) {
            // Reserve primary for topology version or explicit partitions.
            reserved = h2.partitionReservationManager().reservePartitions(cacheIds, topVer, parts, node.id(), reqId);
            if (reserved.failed()) {
                sendRetry(node, reqId, segmentId, reserved.error());
                return;
            }
        }
        // Prepare query context.
        DistributedJoinContext distributedJoinCtx = null;
        if (distributedJoins && !replicated) {
            distributedJoinCtx = new DistributedJoinContext(topVer, partsMap, node.id(), reqId, segmentId, pageSize);
        }
        qctx = new QueryContext(segmentId, h2.backupFilter(topVer, parts, treatReplicatedAsPartitioned), distributedJoinCtx, mvccSnapshot, reserved, true);
        qryResults = new MapQueryResults(h2, reqId, qrys.size(), mainCctx, lazy, qctx);
        // qctx is set, we have to release reservations inside of it.
        reserved = null;
        if (distributedJoinCtx != null)
            qryCtxRegistry.setShared(node.id(), reqId, qctx);
        if (nodeRess.put(reqId, segmentId, qryResults) != null)
            throw new IllegalStateException();
        if (nodeRess.cancelled(reqId)) {
            qryCtxRegistry.clearShared(node.id(), reqId);
            nodeRess.cancelRequest(reqId);
            throw new QueryCancelledException();
        }
        // Run queries.
        int qryIdx = 0;
        boolean evt = mainCctx != null && mainCctx.events().isRecordable(EVT_CACHE_QUERY_EXECUTED);
        for (GridCacheSqlQuery qry : qrys) {
            H2PooledConnection conn = h2.connections().connection(schemaName);
            H2Utils.setupConnection(conn, qctx, distributedJoins, enforceJoinOrder, lazy);
            MapQueryResult res = new MapQueryResult(h2, mainCctx, node.id(), qry, params, conn, log);
            qryResults.addResult(qryIdx, res);
            try {
                res.lock();
                // Ensure we are on the target node for this replicated query.
                if (qry.node() == null || (segmentId == 0 && qry.node().equals(ctx.localNodeId()))) {
                    String sql = qry.query();
                    Collection<Object> params0 = F.asList(qry.parameters(params));
                    PreparedStatement stmt = conn.prepareStatement(sql, H2StatementCache.queryFlags(distributedJoins, enforceJoinOrder));
                    H2Utils.bindParameters(stmt, params0);
                    MapH2QueryInfo qryInfo = new MapH2QueryInfo(stmt, qry.query(), node.id(), qryId, reqId, segmentId);
                    ResultSet rs = h2.executeSqlQueryWithTimer(stmt, conn, sql, timeout, qryResults.queryCancel(qryIdx), dataPageScanEnabled, qryInfo);
                    if (evt) {
                        ctx.event().record(new CacheQueryExecutedEvent<>(node, "SQL query executed.", EVT_CACHE_QUERY_EXECUTED, CacheQueryType.SQL.name(), mainCctx.name(), null, qry.query(), null, null, params, node.id(), null));
                    }
                    assert rs instanceof JdbcResultSet : rs.getClass();
                    if (qryResults.cancelled()) {
                        rs.close();
                        throw new QueryCancelledException();
                    }
                    res.openResult(rs, qryInfo);
                    final GridQueryNextPageResponse msg = prepareNextPage(nodeRess, node, qryResults, qryIdx, segmentId, pageSize, dataPageScanEnabled);
                    if (msg != null)
                        sendNextPage(node, msg);
                } else {
                    assert !qry.isPartitioned();
                    qryResults.closeResult(qryIdx);
                }
                qryIdx++;
            } finally {
                try {
                    res.unlockTables();
                } finally {
                    res.unlock();
                }
            }
        }
        if (!lazy)
            qryResults.releaseQueryContext();
    } catch (Throwable e) {
        if (qryResults != null) {
            nodeRess.remove(reqId, segmentId, qryResults);
            qryResults.close();
            // If a query is cancelled before execution is started partitions have to be released.
            if (!lazy || !qryResults.isAllClosed())
                qryResults.releaseQueryContext();
        } else
            releaseReservations(qctx);
        if (e instanceof QueryCancelledException)
            sendError(node, reqId, e);
        else {
            SQLException sqlEx = X.cause(e, SQLException.class);
            if (sqlEx != null && sqlEx.getErrorCode() == ErrorCode.STATEMENT_WAS_CANCELED)
                sendQueryCancel(node, reqId);
            else {
                GridH2RetryException retryErr = X.cause(e, GridH2RetryException.class);
                if (retryErr != null) {
                    final String retryCause = String.format("Failed to execute non-collocated query (will retry) [localNodeId=%s, rmtNodeId=%s, reqId=%s, " + "errMsg=%s]", ctx.localNodeId(), node.id(), reqId, retryErr.getMessage());
                    sendRetry(node, reqId, segmentId, retryCause);
                } else {
                    QueryRetryException qryRetryErr = X.cause(e, QueryRetryException.class);
                    if (qryRetryErr != null)
                        sendError(node, reqId, qryRetryErr);
                    else {
                        if (e instanceof Error) {
                            U.error(log, "Failed to execute local query.", e);
                            throw (Error) e;
                        }
                        U.warn(log, "Failed to execute local query.", e);
                        sendError(node, reqId, e);
                    }
                }
            }
        }
    } finally {
        if (reserved != null)
            reserved.release();
        if (trace != null)
            trace.close();
        if (performanceStatsEnabled) {
            IoStatisticsHolder stat = IoStatisticsQueryHelper.finishGatheringQueryStatistics();
            if (stat.logicalReads() > 0 || stat.physicalReads() > 0) {
                ctx.performanceStatistics().queryReads(GridCacheQueryType.SQL_FIELDS, node.id(), reqId, stat.logicalReads(), stat.physicalReads());
            }
        }
    }
}
Also used : QueryRetryException(org.apache.ignite.cache.query.QueryRetryException) SQLException(java.sql.SQLException) GridQueryNextPageResponse(org.apache.ignite.internal.processors.query.h2.twostep.messages.GridQueryNextPageResponse) TraceSurroundings(org.apache.ignite.internal.processors.tracing.MTC.TraceSurroundings) DistributedJoinContext(org.apache.ignite.internal.processors.query.h2.opt.join.DistributedJoinContext) ResultSet(java.sql.ResultSet) JdbcResultSet(org.h2.jdbc.JdbcResultSet) GridCacheSqlQuery(org.apache.ignite.internal.processors.cache.query.GridCacheSqlQuery) JdbcResultSet(org.h2.jdbc.JdbcResultSet) H2PooledConnection(org.apache.ignite.internal.processors.query.h2.H2PooledConnection) MapH2QueryInfo(org.apache.ignite.internal.processors.query.h2.MapH2QueryInfo) GridH2RetryException(org.apache.ignite.internal.processors.query.h2.opt.GridH2RetryException) PreparedStatement(java.sql.PreparedStatement) QueryContext(org.apache.ignite.internal.processors.query.h2.opt.QueryContext) IoStatisticsHolder(org.apache.ignite.internal.metric.IoStatisticsHolder) QueryCancelledException(org.apache.ignite.cache.query.QueryCancelledException)

Example 8 with JdbcResultSet

use of org.h2.jdbc.JdbcResultSet in project h2database by h2database.

the class PgServerThread method writeDataColumn.

private void writeDataColumn(ResultSet rs, int column, int pgType, boolean text) throws Exception {
    Value v = ((JdbcResultSet) rs).get(column);
    if (v == ValueNull.INSTANCE) {
        writeInt(-1);
        return;
    }
    if (text) {
        // plain text
        switch(pgType) {
            case PgServer.PG_TYPE_BOOL:
                writeInt(1);
                dataOut.writeByte(v.getBoolean() ? 't' : 'f');
                break;
            default:
                byte[] data = v.getString().getBytes(getEncoding());
                writeInt(data.length);
                write(data);
        }
    } else {
        // binary
        switch(pgType) {
            case PgServer.PG_TYPE_INT2:
                writeInt(2);
                writeShort(v.getShort());
                break;
            case PgServer.PG_TYPE_INT4:
                writeInt(4);
                writeInt(v.getInt());
                break;
            case PgServer.PG_TYPE_INT8:
                writeInt(8);
                dataOut.writeLong(v.getLong());
                break;
            case PgServer.PG_TYPE_FLOAT4:
                writeInt(4);
                dataOut.writeFloat(v.getFloat());
                break;
            case PgServer.PG_TYPE_FLOAT8:
                writeInt(8);
                dataOut.writeDouble(v.getDouble());
                break;
            case PgServer.PG_TYPE_BYTEA:
                {
                    byte[] data = v.getBytesNoCopy();
                    writeInt(data.length);
                    write(data);
                    break;
                }
            case PgServer.PG_TYPE_DATE:
                {
                    ValueDate d = (ValueDate) v.convertTo(Value.DATE);
                    writeInt(4);
                    writeInt((int) (toPostgreDays(d.getDateValue())));
                    break;
                }
            case PgServer.PG_TYPE_TIME:
                {
                    ValueTime t = (ValueTime) v.convertTo(Value.TIME);
                    writeInt(8);
                    long m = t.getNanos();
                    if (INTEGER_DATE_TYPES) {
                        // long format
                        m /= 1_000;
                    } else {
                        // double format
                        m = Double.doubleToLongBits(m * 0.000_000_001);
                    }
                    dataOut.writeLong(m);
                    break;
                }
            case PgServer.PG_TYPE_TIMESTAMP_NO_TMZONE:
                {
                    ValueTimestamp t = (ValueTimestamp) v.convertTo(Value.TIMESTAMP);
                    writeInt(8);
                    long m = toPostgreDays(t.getDateValue()) * 86_400;
                    long nanos = t.getTimeNanos();
                    if (INTEGER_DATE_TYPES) {
                        // long format
                        m = m * 1_000_000 + nanos / 1_000;
                    } else {
                        // double format
                        m = Double.doubleToLongBits(m + nanos * 0.000_000_001);
                    }
                    dataOut.writeLong(m);
                    break;
                }
            default:
                throw new IllegalStateException("output binary format is undefined");
        }
    }
}
Also used : ValueTime(org.h2.value.ValueTime) ValueTimestamp(org.h2.value.ValueTimestamp) Value(org.h2.value.Value) ValueDate(org.h2.value.ValueDate) JdbcResultSet(org.h2.jdbc.JdbcResultSet)

Example 9 with JdbcResultSet

use of org.h2.jdbc.JdbcResultSet in project h2database by h2database.

the class JdbcPreparedStatement method execute.

/**
 * Executes an arbitrary statement. If another result set exists for this
 * statement, this will be closed (even if this statement fails). If auto
 * commit is on, and the statement is not a select, this statement will be
 * committed.
 *
 * @return true if a result set is available, false if not
 * @throws SQLException if this object is closed or invalid
 */
@Override
public boolean execute() throws SQLException {
    try {
        int id = getNextId(TraceObject.RESULT_SET);
        if (isDebugEnabled()) {
            debugCodeCall("execute");
        }
        checkClosedForWrite();
        try {
            boolean returnsResultSet;
            synchronized (conn.getSession()) {
                closeOldResultSet();
                boolean lazy = false;
                try {
                    setExecutingStatement(command);
                    if (command.isQuery()) {
                        returnsResultSet = true;
                        boolean scrollable = resultSetType != ResultSet.TYPE_FORWARD_ONLY;
                        boolean updatable = resultSetConcurrency == ResultSet.CONCUR_UPDATABLE;
                        ResultInterface result = command.executeQuery(maxRows, scrollable);
                        lazy = result.isLazy();
                        resultSet = new JdbcResultSet(conn, this, command, result, id, closedByResultSet, scrollable, updatable, cachedColumnLabelMap);
                    } else {
                        returnsResultSet = false;
                        ResultWithGeneratedKeys result = command.executeUpdate(generatedKeysRequest);
                        updateCount = result.getUpdateCount();
                        ResultInterface gk = result.getGeneratedKeys();
                        if (gk != null) {
                            generatedKeys = new JdbcResultSet(conn, this, command, gk, id, false, true, false);
                        }
                    }
                } finally {
                    if (!lazy) {
                        setExecutingStatement(null);
                    }
                }
            }
            return returnsResultSet;
        } finally {
            afterWriting();
        }
    } catch (Throwable e) {
        throw logAndConvert(e);
    }
}
Also used : ResultInterface(org.h2.result.ResultInterface) ResultWithGeneratedKeys(org.h2.result.ResultWithGeneratedKeys)

Example 10 with JdbcResultSet

use of org.h2.jdbc.JdbcResultSet in project h2database by h2database.

the class JdbcPreparedStatement method executeQuery.

/**
 * Executes a query (select statement) and returns the result set. If
 * another result set exists for this statement, this will be closed (even
 * if this statement fails).
 *
 * @return the result set
 * @throws SQLException if this object is closed or invalid
 */
@Override
public ResultSet executeQuery() throws SQLException {
    try {
        int id = getNextId(TraceObject.RESULT_SET);
        if (isDebugEnabled()) {
            debugCodeAssign("ResultSet", TraceObject.RESULT_SET, id, "executeQuery()");
        }
        batchIdentities = null;
        synchronized (session) {
            checkClosed();
            closeOldResultSet();
            ResultInterface result;
            boolean lazy = false;
            boolean scrollable = resultSetType != ResultSet.TYPE_FORWARD_ONLY;
            boolean updatable = resultSetConcurrency == ResultSet.CONCUR_UPDATABLE;
            try {
                setExecutingStatement(command);
                result = command.executeQuery(maxRows, scrollable);
                lazy = result.isLazy();
            } finally {
                if (!lazy) {
                    setExecutingStatement(null);
                }
            }
            resultSet = new JdbcResultSet(conn, this, command, result, id, closedByResultSet, scrollable, updatable, cachedColumnLabelMap);
        }
        return resultSet;
    } catch (Exception e) {
        throw logAndConvert(e);
    }
}
Also used : ResultInterface(org.h2.result.ResultInterface) DbException(org.h2.message.DbException) SQLException(java.sql.SQLException)

Aggregations

ResultInterface (org.h2.result.ResultInterface)7 JdbcResultSet (org.h2.jdbc.JdbcResultSet)4 ResultWithGeneratedKeys (org.h2.result.ResultWithGeneratedKeys)4 ResultSet (java.sql.ResultSet)3 SQLException (java.sql.SQLException)3 QueryCancelledException (org.apache.ignite.cache.query.QueryCancelledException)3 GridCacheSqlQuery (org.apache.ignite.internal.processors.cache.query.GridCacheSqlQuery)3 GridH2RetryException (org.apache.ignite.internal.processors.query.h2.opt.GridH2RetryException)3 CommandInterface (org.h2.command.CommandInterface)3 Connection (java.sql.Connection)2 ArrayList (java.util.ArrayList)2 GridReservable (org.apache.ignite.internal.processors.cache.distributed.dht.GridReservable)2 GridH2QueryContext (org.apache.ignite.internal.processors.query.h2.opt.GridH2QueryContext)2 DbException (org.h2.message.DbException)2 PreparedStatement (java.sql.PreparedStatement)1 QueryRetryException (org.apache.ignite.cache.query.QueryRetryException)1 IoStatisticsHolder (org.apache.ignite.internal.metric.IoStatisticsHolder)1 QueryTable (org.apache.ignite.internal.processors.cache.query.QueryTable)1 H2PooledConnection (org.apache.ignite.internal.processors.query.h2.H2PooledConnection)1 MapH2QueryInfo (org.apache.ignite.internal.processors.query.h2.MapH2QueryInfo)1