Search in sources :

Example 11 with ResultsFuture

use of org.teiid.client.util.ResultsFuture in project teiid by teiid.

the class TestAsynch method testTransactionCycle.

@Test
public void testTransactionCycle() throws Exception {
    Statement stmt = this.internalConnection.createStatement();
    TeiidStatement ts = stmt.unwrap(TeiidStatement.class);
    final ResultsFuture<Void> result = new ResultsFuture<Void>();
    ts.submitExecute("start transaction", new StatementCallback() {

        @Override
        public void onRow(Statement s, ResultSet rs) {
        }

        @Override
        public void onException(Statement s, Exception e) {
            result.getResultsReceiver().exceptionOccurred(e);
        }

        @Override
        public void onComplete(Statement s) {
            result.getResultsReceiver().receiveResults(null);
        }
    }, new RequestOptions());
    result.get();
    final ResultsFuture<Void> rollBackResult = new ResultsFuture<Void>();
    ts.submitExecute("rollback", new StatementCallback() {

        @Override
        public void onRow(Statement s, ResultSet rs) {
        }

        @Override
        public void onException(Statement s, Exception e) {
            rollBackResult.getResultsReceiver().exceptionOccurred(e);
        }

        @Override
        public void onComplete(Statement s) {
            rollBackResult.getResultsReceiver().receiveResults(null);
        }
    }, new RequestOptions());
    rollBackResult.get();
}
Also used : ResultsFuture(org.teiid.client.util.ResultsFuture) ContinuousStatementCallback(org.teiid.jdbc.ContinuousStatementCallback) StatementCallback(org.teiid.jdbc.StatementCallback) RequestOptions(org.teiid.jdbc.RequestOptions) TeiidStatement(org.teiid.jdbc.TeiidStatement) Statement(java.sql.Statement) TeiidStatement(org.teiid.jdbc.TeiidStatement) ResultSet(java.sql.ResultSet) TeiidResultSet(org.teiid.jdbc.TeiidResultSet) AsynchPositioningException(org.teiid.jdbc.AsynchPositioningException) SQLException(java.sql.SQLException) TranslatorException(org.teiid.translator.TranslatorException) Test(org.junit.Test)

Example 12 with ResultsFuture

use of org.teiid.client.util.ResultsFuture in project teiid by teiid.

the class StatementImpl method executeSql.

@SuppressWarnings("unchecked")
protected ResultsFuture<Boolean> executeSql(String[] commands, boolean isBatchedCommand, ResultsMode resultsMode, boolean synch, RequestOptions options, boolean autoGenerateKeys) throws SQLException {
    checkStatement();
    resetExecutionState();
    if (options != null) {
        if (options.isContinuous()) {
            if (!this.driverConnection.getServerConnection().supportsContinuous()) {
                // $NON-NLS-1$
                throw new TeiidSQLException(JDBCPlugin.Util.getString("JDBC.continuous"));
            }
            if (this.getResultSetType() != ResultSet.TYPE_FORWARD_ONLY) {
                // $NON-NLS-1$
                String msg = JDBCPlugin.Util.getString("JDBC.forward_only_resultset");
                throw new TeiidSQLException(msg);
            }
            if (resultsMode == ResultsMode.EITHER) {
                resultsMode = ResultsMode.RESULTSET;
            } else if (resultsMode == ResultsMode.UPDATECOUNT) {
                // $NON-NLS-1$
                String msg = JDBCPlugin.Util.getString("JDBC.forward_only_resultset");
                throw new TeiidSQLException(msg);
            }
        }
    }
    if (logger.isLoggable(Level.FINER)) {
        // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        logger.finer("Executing: requestID " + getCurrentRequestID() + " commands: " + Arrays.toString(commands) + " expecting: " + resultsMode);
    }
    if (commands.length == 1) {
        Matcher match = SET_STATEMENT.matcher(commands[0]);
        if (match.matches()) {
            if (resultsMode == ResultsMode.RESULTSET) {
                // $NON-NLS-1$
                throw new TeiidSQLException(JDBCPlugin.Util.getString("StatementImpl.set_result_set"));
            }
            String val = match.group(2);
            String key = unescapeId(val);
            String value = match.group(3);
            if (value != null && value.startsWith("\'") && value.endsWith("\'")) {
                // $NON-NLS-1$ //$NON-NLS-2$
                value = value.substring(1, value.length() - 1);
                // $NON-NLS-1$ //$NON-NLS-2$
                value = StringUtil.replaceAll(value, "''", "'");
            }
            if (match.group(1) != null) {
                // payload case
                Properties p = this.getMMConnection().getPayload();
                if (p == null) {
                    p = new Properties();
                    this.getMMConnection().setPayload(p);
                }
                p.setProperty(key, value);
            } else if (val == key && "SESSION AUTHORIZATION".equalsIgnoreCase(key)) {
                // $NON-NLS-1$
                this.getMMConnection().changeUser(value, this.getMMConnection().getPassword());
            } else if (key.equalsIgnoreCase(TeiidURL.CONNECTION.PASSWORD)) {
                this.getMMConnection().setPassword(value);
            } else if (ExecutionProperties.NEWINSTANCE.equalsIgnoreCase(key)) {
                if (Boolean.valueOf(value)) {
                    this.getMMConnection().getServerConnection().cleanUp();
                }
            } else {
                this.driverConnection.setExecutionProperty(key, value);
            }
            this.updateCounts = new int[] { 0 };
            return booleanFuture(false);
        }
        match = SET_CHARACTERISTIC_STATEMENT.matcher(commands[0]);
        if (match.matches()) {
            String value = match.group(1);
            if (StringUtil.endsWithIgnoreCase(value, "uncommitted")) {
                // $NON-NLS-1$
                this.getMMConnection().setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
            } else if (StringUtil.endsWithIgnoreCase(value, "committed")) {
                // $NON-NLS-1$
                this.getMMConnection().setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            } else if (StringUtil.startsWithIgnoreCase(value, "repeatable")) {
                // $NON-NLS-1$
                this.getMMConnection().setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
            } else if ("serializable".equalsIgnoreCase(value)) {
                // $NON-NLS-1$
                this.getMMConnection().setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
            }
            this.updateCounts = new int[] { 0 };
            return booleanFuture(false);
        }
        match = TRANSACTION_STATEMENT.matcher(commands[0]);
        if (match.matches()) {
            // $NON-NLS-1$
            logger.finer("Executing as transaction statement");
            if (resultsMode == ResultsMode.RESULTSET) {
                // $NON-NLS-1$
                throw new TeiidSQLException(JDBCPlugin.Util.getString("StatementImpl.set_result_set"));
            }
            String command = match.group(1);
            Boolean commit = null;
            if (StringUtil.startsWithIgnoreCase(command, "start")) {
                // $NON-NLS-1$
                // TODO: this should force a start and through an exception if we're already in a txn
                this.getConnection().setAutoCommit(false);
            } else if (command.equalsIgnoreCase("commit")) {
                // $NON-NLS-1$
                commit = true;
                if (synch) {
                    this.getConnection().setAutoCommit(true);
                }
            } else if (command.equalsIgnoreCase("rollback")) {
                // $NON-NLS-1$
                commit = false;
                if (synch || !this.getConnection().isInLocalTxn()) {
                    this.getConnection().rollback(false);
                }
            }
            this.updateCounts = new int[] { 0 };
            if (commit != null && !synch) {
                ResultsFuture<?> pending = this.getConnection().submitSetAutoCommitTrue(commit);
                final ResultsFuture<Boolean> result = new ResultsFuture<Boolean>();
                pending.addCompletionListener(new ResultsFuture.CompletionListener() {

                    @Override
                    public void onCompletion(ResultsFuture future) {
                        try {
                            future.get();
                            result.getResultsReceiver().receiveResults(false);
                        } catch (Throwable t) {
                            result.getResultsReceiver().exceptionOccurred(t);
                        }
                    }
                });
                return result;
            }
            return booleanFuture(false);
        }
        match = SHOW_STATEMENT.matcher(commands[0]);
        if (match.matches()) {
            // $NON-NLS-1$
            logger.finer("Executing as show statement");
            if (resultsMode == ResultsMode.UPDATECOUNT) {
                // $NON-NLS-1$
                throw new TeiidSQLException(JDBCPlugin.Util.getString("StatementImpl.show_update_count"));
            }
            return executeShow(match);
        }
    }
    final RequestMessage reqMessage = createRequestMessage(commands, isBatchedCommand, resultsMode);
    reqMessage.setReturnAutoGeneratedKeys(autoGenerateKeys);
    reqMessage.setRequestOptions(options);
    ResultsFuture<ResultsMessage> pendingResult = execute(reqMessage, synch);
    final ResultsFuture<Boolean> result = new ResultsFuture<Boolean>();
    pendingResult.addCompletionListener(new ResultsFuture.CompletionListener<ResultsMessage>() {

        @Override
        public void onCompletion(ResultsFuture<ResultsMessage> future) {
            try {
                postReceiveResults(reqMessage, future.get());
                result.getResultsReceiver().receiveResults(hasResultSet());
            } catch (Throwable t) {
                result.getResultsReceiver().exceptionOccurred(t);
            }
        }
    });
    if (synch) {
        try {
            pendingResult.get(queryTimeoutMS == 0 ? Integer.MAX_VALUE : queryTimeoutMS, TimeUnit.MILLISECONDS);
            // throw an exception if needed
            result.get();
            return result;
        } catch (ExecutionException e) {
            if (e.getCause() instanceof SQLException) {
                throw (SQLException) e.getCause();
            }
            if (e.getCause() != null) {
                throw TeiidSQLException.create(e.getCause());
            }
            throw TeiidSQLException.create(e);
        } catch (InterruptedException e) {
            timeoutOccurred();
        } catch (TimeoutException e) {
            timeoutOccurred();
        }
        // $NON-NLS-1$
        throw new TeiidSQLException(JDBCPlugin.Util.getString("MMStatement.Timeout_before_complete"));
    }
    return result;
}
Also used : Matcher(java.util.regex.Matcher) SQLException(java.sql.SQLException) ResultsMessage(org.teiid.client.ResultsMessage) ResultsFuture(org.teiid.client.util.ResultsFuture) RequestMessage(org.teiid.client.RequestMessage) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Example 13 with ResultsFuture

use of org.teiid.client.util.ResultsFuture in project teiid by teiid.

the class ODBCServerRemoteImpl method sendPortalResults.

private void sendPortalResults(final int maxRows, final Portal query) {
    if (query.rs != null) {
        // this is a suspended portal
        sendCursorResults(query, maxRows);
        return;
    }
    final PreparedStatementImpl stmt = query.stmt;
    try {
        this.executionFuture = stmt.submitExecute(ResultsMode.EITHER, null);
        executionFuture.addCompletionListener(new ResultsFuture.CompletionListener<Boolean>() {

            @Override
            public void onCompletion(ResultsFuture<Boolean> future) {
                executionFuture = null;
                try {
                    if (future.get()) {
                        query.rs = stmt.getResultSet();
                        sendCursorResults(query, maxRows);
                    } else {
                        client.sendUpdateCount(query.prepared.sql, stmt.getUpdateCount());
                        updateSessionProperties();
                        doneExecuting();
                    }
                } catch (ExecutionException e) {
                    if (e.getCause() != null) {
                        errorOccurred(e.getCause());
                    } else {
                        errorOccurred(e);
                    }
                } catch (Throwable e) {
                    errorOccurred(e);
                }
            }
        });
    } catch (SQLException e) {
        errorOccurred(e);
    }
}
Also used : ResultsFuture(org.teiid.client.util.ResultsFuture) TeiidSQLException(org.teiid.jdbc.TeiidSQLException) SQLException(java.sql.SQLException) PreparedStatementImpl(org.teiid.jdbc.PreparedStatementImpl) ExecutionException(java.util.concurrent.ExecutionException)

Example 14 with ResultsFuture

use of org.teiid.client.util.ResultsFuture in project teiid by teiid.

the class ODBCServerRemoteImpl method cursorExecute.

private void cursorExecute(String cursorName, final String sql, final ResultsFuture<Integer> completion, boolean scroll, final boolean binary) {
    try {
        // close if the name is already used or the unnamed prepare; otherwise
        // stmt is alive until session ends.
        this.preparedMap.remove(UNNAMED);
        Portal p = this.portalMap.remove(UNNAMED);
        if (p != null) {
            closePortal(p);
        }
        if (cursorName == null || cursorName.length() == 0) {
            cursorName = UNNAMED;
        }
        Cursor cursor = cursorMap.get(cursorName);
        if (cursor != null) {
            errorOccurred(RuntimePlugin.Util.gs(RuntimePlugin.Event.TEIID40111, cursorName));
            return;
        }
        final PreparedStatementImpl stmt = this.connection.prepareStatement(sql, scroll ? ResultSet.TYPE_SCROLL_INSENSITIVE : ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        this.executionFuture = stmt.submitExecute(ResultsMode.RESULTSET, null);
        final String name = cursorName;
        this.executionFuture.addCompletionListener(new ResultsFuture.CompletionListener<Boolean>() {

            @Override
            public void onCompletion(ResultsFuture<Boolean> future) {
                executionFuture = null;
                try {
                    if (future.get()) {
                        List<PgColInfo> cols = getPgColInfo(stmt.getResultSet().getMetaData());
                        cursorMap.put(name, new Cursor(name, sql, stmt, stmt.getResultSet(), cols, binary));
                        // $NON-NLS-1$
                        client.sendCommandComplete("DECLARE CURSOR", null);
                        completion.getResultsReceiver().receiveResults(0);
                    }
                } catch (Throwable e) {
                    completion.getResultsReceiver().exceptionOccurred(e);
                }
            }
        });
    } catch (SQLException e) {
        completion.getResultsReceiver().exceptionOccurred(e);
    }
}
Also used : ResultsFuture(org.teiid.client.util.ResultsFuture) TeiidSQLException(org.teiid.jdbc.TeiidSQLException) SQLException(java.sql.SQLException) PreparedStatementImpl(org.teiid.jdbc.PreparedStatementImpl) List(java.util.List) ArrayList(java.util.ArrayList)

Example 15 with ResultsFuture

use of org.teiid.client.util.ResultsFuture in project teiid by teiid.

the class StatementImpl method execute.

private ResultsFuture<ResultsMessage> execute(final RequestMessage reqMsg, boolean synch) throws SQLException, TeiidSQLException {
    this.getConnection().beginLocalTxnIfNeeded();
    this.currentRequestID = this.driverConnection.nextRequestID();
    // Create a request message
    if (this.payload != null) {
        reqMsg.setExecutionPayload(this.payload);
    } else {
        reqMsg.setExecutionPayload(this.getMMConnection().getPayload());
    }
    reqMsg.setDelaySerialization(true);
    reqMsg.setCursorType(this.resultSetType);
    reqMsg.setFetchSize(this.fetchSize);
    reqMsg.setRowLimit(this.maxRows);
    reqMsg.setTransactionIsolation(this.driverConnection.getTransactionIsolation());
    reqMsg.setSync(synch && useCallingThread());
    // Get connection properties and set them onto request message
    copyPropertiesToRequest(reqMsg);
    reqMsg.setExecutionId(this.currentRequestID);
    ResultsFuture.CompletionListener<ResultsMessage> compeletionListener = null;
    if (queryTimeoutMS > 0 && (!synch || this.driverConnection.getServerConnection().isLocal())) {
        final Task c = cancellationTimer.add(cancelTask, queryTimeoutMS);
        compeletionListener = new ResultsFuture.CompletionListener<ResultsMessage>() {

            @Override
            public void onCompletion(ResultsFuture<ResultsMessage> future) {
                c.cancel();
            }
        };
    }
    ResultsFuture<ResultsMessage> pendingResult = null;
    try {
        pendingResult = this.getDQP().executeRequest(this.currentRequestID, reqMsg);
    } catch (TeiidException e) {
        throw TeiidSQLException.create(e);
    }
    if (compeletionListener != null) {
        pendingResult.addCompletionListener(compeletionListener);
    }
    return pendingResult;
}
Also used : ResultsFuture(org.teiid.client.util.ResultsFuture) Task(org.teiid.jdbc.EnhancedTimer.Task) ResultsMessage(org.teiid.client.ResultsMessage) TeiidException(org.teiid.core.TeiidException)

Aggregations

ResultsFuture (org.teiid.client.util.ResultsFuture)34 Test (org.junit.Test)21 SQLException (java.sql.SQLException)17 ResultsMessage (org.teiid.client.ResultsMessage)13 TranslatorException (org.teiid.translator.TranslatorException)11 ResultSet (java.sql.ResultSet)10 Statement (java.sql.Statement)10 RequestOptions (org.teiid.jdbc.RequestOptions)10 TeiidStatement (org.teiid.jdbc.TeiidStatement)10 AsynchPositioningException (org.teiid.jdbc.AsynchPositioningException)9 ContinuousStatementCallback (org.teiid.jdbc.ContinuousStatementCallback)9 TeiidResultSet (org.teiid.jdbc.TeiidResultSet)9 Properties (java.util.Properties)8 ExecutionException (java.util.concurrent.ExecutionException)8 StatementCallback (org.teiid.jdbc.StatementCallback)8 DQP (org.teiid.client.DQP)7 RequestMessage (org.teiid.client.RequestMessage)5 TeiidComponentException (org.teiid.core.TeiidComponentException)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4