Search in sources :

Example 1 with Query

use of net.sourceforge.sqlexplorer.parsers.Query in project tdq-studio-se by Talend.

the class ExplainExecution method doExecution.

protected void doExecution(IProgressMonitor monitor) throws Exception {
    int numErrors;
    SQLException lastSQLException;
    Query query;
    numErrors = 0;
    lastSQLException = null;
    query = null;
    Iterator iter = getQueryParser().iterator();
    String id_;
    query = (Query) iter.next();
    if (monitor.isCanceled()) {
        return;
    }
    _stmt = _connection.createStatement();
    id_ = Integer.toHexString((new Random()).nextInt()).toUpperCase();
    _stmt.execute((new StringBuilder("delete plan_table where statement_id='")).append(id_).append("'").toString());
    _stmt.close();
    _stmt = null;
    if (monitor.isCanceled())
        return;
    ResultSet rs;
    ExplainNode nd_parent;
    try {
        _stmt = _connection.createStatement();
        _stmt.execute((new StringBuilder("EXPLAIN PLAN SET statement_id = '")).append(id_).append("' FOR ").append(query.getQuerySql()).toString());
        _stmt.close();
        _stmt = null;
        if (monitor.isCanceled())
            return;
    } catch (SQLException e) {
        debugLogQuery(query, e);
        boolean stopOnError = SQLExplorerPlugin.getDefault().getPreferenceStore().getBoolean("SQLEditor.StopOnError");
        logException(e, query, stopOnError);
        closeStatements();
        if (stopOnError)
            throw e;
        numErrors++;
        lastSQLException = e;
    } catch (Exception e) {
        closeStatements();
        throw e;
    }
    _prepStmt = _connection.prepareStatement("select level, object_type,operation,options,object_owner,object_name,optimizer,cardinality ,cost,id,parent_id,level  from  plan_table  start with id = 0 and statement_id=?  connect by prior id=parent_id and statement_id=?");
    _prepStmt.setString(1, id_);
    _prepStmt.setString(2, id_);
    rs = _prepStmt.executeQuery();
    if (monitor.isCanceled())
        return;
    HashMap mp = new HashMap();
    int level;
    ExplainNode nd;
    for (; rs.next(); nd.setLevel(level)) {
        String object_type = rs.getString("object_type");
        String operation = rs.getString("operation");
        String options = rs.getString("options");
        String object_owner = rs.getString("object_owner");
        String object_name = rs.getString("object_name");
        String optimizer = rs.getString("optimizer");
        int cardinality = rs.getInt("cardinality");
        if (rs.wasNull())
            cardinality = -1;
        int cost = rs.getInt("cost");
        if (rs.wasNull())
            cost = -1;
        int parentID = rs.getInt("parent_id");
        int id = rs.getInt("id");
        level = rs.getInt("level");
        nd = null;
        if (id == 0) {
            ExplainNode dummy = new ExplainNode(null);
            mp.put(new Integer(-1), dummy);
            dummy.setId(-1);
            nd = new ExplainNode(dummy);
            dummy.add(nd);
            nd.setId(0);
            mp.put(new Integer(0), nd);
        } else {
            nd_parent = (ExplainNode) mp.get(new Integer(parentID));
            nd = new ExplainNode(nd_parent);
            nd_parent.add(nd);
            mp.put(new Integer(id), nd);
        }
        nd.setCardinality(cardinality);
        nd.setCost(cost);
        nd.setObject_name(object_name);
        nd.setObject_owner(object_owner);
        nd.setObject_type(object_type);
        nd.setOperation(operation);
        nd.setOptimizer(optimizer);
        nd.setOptions(options);
        nd.setId(id);
    }
    rs.close();
    _prepStmt.close();
    _prepStmt = null;
    nd_parent = (ExplainNode) mp.get(new Integer(-1));
    if (monitor.isCanceled())
        return;
    displayResults(nd_parent, query);
    debugLogQuery(query, null);
    query = null;
    if (numErrors == 1)
        throw lastSQLException;
    if (numErrors > 1)
        MessageDialog.openError(getEditor().getSite().getShell(), "SQL Error", "One or more of your SQL statements failed - check the Messages log for details");
    return;
}
Also used : Query(net.sourceforge.sqlexplorer.parsers.Query) Random(java.util.Random) ExplainNode(net.sourceforge.sqlexplorer.oracle.actions.explain.ExplainNode) SQLException(java.sql.SQLException) HashMap(java.util.HashMap) Iterator(java.util.Iterator) ResultSet(java.sql.ResultSet) SQLException(java.sql.SQLException)

Example 2 with Query

use of net.sourceforge.sqlexplorer.parsers.Query in project tdq-studio-se by Talend.

the class SQLExecution method displayResults.

/**
 * Display SQL Results in result pane
 * @param sqlResult the results of the query
 */
protected void displayResults(final SQLResult sqlResult) {
    // Switch to the UI thread to execute this
    getEditor().getSite().getShell().getDisplay().asyncExec(new Runnable() {

        public void run() {
            ResultsTab resultsTab = allocateResultsTab(sqlResult.getQuery());
            if (resultsTab == null)
                return;
            String caption = sqlResult.getDataSet().getCaption();
            if (caption != null)
                resultsTab.getTabItem().setText(caption);
            try {
                // set initial message
                setProgressMessage(Messages.getString("SQLResultsView.ConnectionWait"));
                Composite composite = resultsTab.getParent();
                GridLayout gLayout = new GridLayout();
                gLayout.numColumns = 2;
                gLayout.marginLeft = 0;
                gLayout.horizontalSpacing = 0;
                gLayout.verticalSpacing = 0;
                gLayout.marginWidth = 0;
                gLayout.marginHeight = 0;
                composite.setLayout(gLayout);
                int resultCount = sqlResult.getDataSet().getRows().length;
                String statusMessage = Messages.getString("SQLResultsView.Time.Prefix") + " " + sqlResult.getExecutionTimeMillis() + " " + Messages.getString("SQLResultsView.Time.Postfix");
                getEditor().setMessage(statusMessage);
                if (resultCount > 0)
                    statusMessage = statusMessage + "  " + Messages.getString("SQLResultsView.Count.Prefix") + " " + resultCount;
                Query sql = sqlResult.getQuery();
                int lineNo = sql.getLineNo();
                lineNo = getQueryParser().adjustLineNo(lineNo);
                getEditor().addMessage(new Message(Message.Status.SUCCESS, lineNo, 0, sql.getQuerySql(), statusMessage));
                new DataSetTable(composite, sqlResult.getDataSet(), statusMessage);
                composite.setData("parenttab", resultsTab.getTabItem());
                composite.layout();
                composite.redraw();
                // reset to start message in case F5 will be used
                setProgressMessage(Messages.getString("SQLResultsView.ConnectionWait"));
            } catch (Exception e) {
                // add message
                if (resultsTab != null) {
                    String message = e.getMessage();
                    Label errorLabel = new Label(resultsTab.getParent(), SWT.FILL);
                    errorLabel.setText(message);
                    errorLabel.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
                }
                SQLExplorerPlugin.error("Error creating result tab", e);
            }
        }
    });
}
Also used : GridLayout(org.eclipse.swt.layout.GridLayout) Composite(org.eclipse.swt.widgets.Composite) Query(net.sourceforge.sqlexplorer.parsers.Query) Message(net.sourceforge.sqlexplorer.plugin.editors.Message) DataSetTable(net.sourceforge.sqlexplorer.dataset.DataSetTable) ResultsTab(net.sourceforge.sqlexplorer.sqleditor.results.ResultsTab) Label(org.eclipse.swt.widgets.Label) GridData(org.eclipse.swt.layout.GridData) SQLException(java.sql.SQLException)

Example 3 with Query

use of net.sourceforge.sqlexplorer.parsers.Query in project tdq-studio-se by Talend.

the class SQLExecution method doExecution.

protected void doExecution(IProgressMonitor monitor) throws Exception {
    int numErrors = 0;
    SQLException lastSQLException = null;
    try {
        long overallUpdateCount = 0;
        long overallStartTime = System.currentTimeMillis();
        for (Query query : getQueryParser()) {
            if (monitor.isCanceled())
                break;
            if (getEditor().isClosed())
                break;
            // Get the next bit of SQL to run and store it as "current"
            if (query == null)
                break;
            String querySQL = query.getQuerySql().toString();
            if (querySQL == null)
                continue;
            // Initialise
            setProgressMessage(Messages.getString("SQLResultsView.Executing"));
            final long startTime = System.currentTimeMillis();
            // Run it
            DatabaseProduct.ExecutionResults results = null;
            try {
                DatabaseProduct product = getEditor().getSession().getDatabaseProduct();
                try {
                    results = product.executeQuery(_connection, query, _maxRows);
                } catch (RuntimeException e) {
                    throw new SQLException(e.getMessage());
                }
                final long endTime = System.currentTimeMillis();
                DataSet dataSet;
                boolean checkedForMessages = false;
                while ((dataSet = results.nextDataSet()) != null) {
                    // update sql result
                    SQLResult sqlResult = new SQLResult();
                    sqlResult.setQuery(query);
                    sqlResult.setDataSet(dataSet);
                    sqlResult.setExecutionTimeMillis(endTime - startTime);
                    // Save successfull query
                    SQLExplorerPlugin.getDefault().getSQLHistory().addSQL(querySQL, _session);
                    if (monitor.isCanceled())
                        return;
                    checkForMessages(query);
                    checkedForMessages = true;
                    // show results..
                    displayResults(sqlResult);
                }
                overallUpdateCount += results.getUpdateCount();
                if (!checkedForMessages)
                    checkForMessages(query);
                debugLogQuery(query, null);
            } catch (final SQLException e) {
                debugLogQuery(query, e);
                boolean stopOnError = SQLExplorerPlugin.getDefault().getPreferenceStore().getBoolean(IConstants.STOP_ON_ERROR);
                logException(e, query, stopOnError);
                closeStatement();
                hasMessages = true;
                if (stopOnError) {
                    errorDialog(Messages.getString("SQLResultsView.Error.Title"), e.getMessage());
                    return;
                }
                numErrors++;
                lastSQLException = e;
            } finally {
                try {
                    if (results != null) {
                        results.close();
                        results = null;
                    }
                } catch (SQLException e) {
                // Nothing
                }
            }
        }
        if (!hasMessages || SQLExplorerPlugin.getDefault().getPreferenceStore().getBoolean(IConstants.LOG_SUCCESS_MESSAGES)) {
            long overallTime = System.currentTimeMillis() - overallStartTime;
            String message = Long.toString(overallUpdateCount) + " " + Messages.getString("SQLEditor.Update.Prefix") + " " + Long.toString(overallTime) + " " + Messages.getString("SQLEditor.Update.Postfix");
            addMessage(new Message(Message.Status.STATUS, getQueryParser().adjustLineNo(1), 0, "", message));
        }
    } catch (Exception e) {
        closeStatement();
        throw e;
    }
    if (numErrors == 1)
        throw lastSQLException;
    else if (numErrors > 1 && SQLExplorerPlugin.getDefault().getPreferenceStore().getBoolean(IConstants.CONFIRM_BOOL_SHOW_DIALOG_ON_QUERY_ERROR))
        getEditor().getSite().getShell().getDisplay().asyncExec(new Runnable() {

            public void run() {
                MessageDialogWithToggle dialog = MessageDialogWithToggle.openInformation(getEditor().getSite().getShell(), Messages.getString("SQLExecution.Error.Title"), Messages.getString("SQLExecution.Error.Message"), Messages.getString("SQLExecution.Error.Toggle"), false, null, null);
                if (dialog.getToggleState() && dialog.getReturnCode() == IDialogConstants.OK_ID)
                    SQLExplorerPlugin.getDefault().getPluginPreferences().setValue(IConstants.CONFIRM_BOOL_SHOW_DIALOG_ON_QUERY_ERROR, false);
            }
        });
}
Also used : Query(net.sourceforge.sqlexplorer.parsers.Query) Message(net.sourceforge.sqlexplorer.plugin.editors.Message) SQLException(java.sql.SQLException) DataSet(net.sourceforge.sqlexplorer.dataset.DataSet) SQLException(java.sql.SQLException) DatabaseProduct(net.sourceforge.sqlexplorer.dbproduct.DatabaseProduct) MessageDialogWithToggle(org.eclipse.jface.dialogs.MessageDialogWithToggle)

Example 4 with Query

use of net.sourceforge.sqlexplorer.parsers.Query in project tdq-studio-se by Talend.

the class BatchJob method run.

@Override
protected IStatus run(IProgressMonitor monitor) {
    monitor.beginTask(Messages.getString("BatchJob.ExecutingScripts"), files.size());
    DatabaseProduct product = user.getAlias().getDriver().getDatabaseProduct();
    SQLConnection connection = null;
    try {
        if (session == null)
            session = user.createSession();
        connection = session.grabConnection();
        int index = 0;
        for (File file : files) {
            if (monitor.isCanceled())
                break;
            monitor.worked(index++);
            monitor.subTask(file.getName());
            _logger.fatal(file.getAbsolutePath());
            String sql = null;
            try {
                char[] buffer = new char[(int) file.length() + 10];
                FileReader reader = new FileReader(file);
                int length = reader.read(buffer);
                reader.close();
                if (length < 0 || length >= buffer.length) {
                    SQLExplorerPlugin.error("Cannot read from file " + file.getAbsolutePath());
                    continue;
                }
                // Normalise this to have standard \n in strings.  \r confuses Oracle and
                // isn't normally needed internally anyway
                StringBuffer sb = new StringBuffer(new String(buffer, 0, length));
                buffer = null;
                for (int i = 0; i < sb.length(); i++) {
                    if (sb.charAt(i) == '\r') {
                        sb.deleteCharAt(i);
                        i--;
                    }
                }
                sql = sb.toString();
                sb = null;
            } catch (IOException e) {
                SQLExplorerPlugin.error("Cannot read from file " + file.getAbsolutePath(), e);
                continue;
            }
            QueryParser parser = product.getQueryParser(sql, 1);
            parser.parse();
            for (Query query : parser) {
                DatabaseProduct.ExecutionResults results = null;
                try {
                    results = product.executeQuery(connection, query, -1);
                    DataSet dataSet;
                    while ((dataSet = results.nextDataSet()) != null) {
                        LinkedList<Message> messages = new LinkedList<Message>();
                        Collection<Message> messagesTmp = session.getDatabaseProduct().getErrorMessages(connection, query);
                        if (messagesTmp != null)
                            messages.addAll(messagesTmp);
                        messagesTmp = session.getDatabaseProduct().getServerMessages(connection);
                        if (messagesTmp != null)
                            messages.addAll(messagesTmp);
                        for (Message msg : messages) msg.setLineNo(parser.adjustLineNo(msg.getLineNo()));
                        for (Message message : messages) {
                            _logger.fatal(message.getSql());
                        }
                    }
                } catch (SQLException e) {
                    _logger.fatal(e.getMessage());
                } finally {
                    try {
                        if (results != null) {
                            results.close();
                            results = null;
                        }
                    } catch (SQLException e) {
                    // Nothing
                    }
                }
            }
        }
        monitor.done();
    } catch (SQLException e) {
        SQLExplorerPlugin.error(e);
    } catch (ParserException e) {
        SQLExplorerPlugin.error(e);
    } finally {
        if (connection != null)
            session.releaseConnection(connection);
    }
    return new Status(IStatus.OK, getClass().getName(), IStatus.OK, Messages.getString("BatchJob.Success"), null);
}
Also used : Status(org.eclipse.core.runtime.Status) IStatus(org.eclipse.core.runtime.IStatus) ParserException(net.sourceforge.sqlexplorer.parsers.ParserException) Query(net.sourceforge.sqlexplorer.parsers.Query) Message(net.sourceforge.sqlexplorer.plugin.editors.Message) DataSet(net.sourceforge.sqlexplorer.dataset.DataSet) SQLException(java.sql.SQLException) SQLConnection(net.sourceforge.sqlexplorer.dbproduct.SQLConnection) IOException(java.io.IOException) LinkedList(java.util.LinkedList) DatabaseProduct(net.sourceforge.sqlexplorer.dbproduct.DatabaseProduct) QueryParser(net.sourceforge.sqlexplorer.parsers.QueryParser) FileReader(java.io.FileReader) File(java.io.File)

Aggregations

SQLException (java.sql.SQLException)4 Query (net.sourceforge.sqlexplorer.parsers.Query)4 Message (net.sourceforge.sqlexplorer.plugin.editors.Message)3 DataSet (net.sourceforge.sqlexplorer.dataset.DataSet)2 DatabaseProduct (net.sourceforge.sqlexplorer.dbproduct.DatabaseProduct)2 File (java.io.File)1 FileReader (java.io.FileReader)1 IOException (java.io.IOException)1 ResultSet (java.sql.ResultSet)1 HashMap (java.util.HashMap)1 Iterator (java.util.Iterator)1 LinkedList (java.util.LinkedList)1 Random (java.util.Random)1 DataSetTable (net.sourceforge.sqlexplorer.dataset.DataSetTable)1 SQLConnection (net.sourceforge.sqlexplorer.dbproduct.SQLConnection)1 ExplainNode (net.sourceforge.sqlexplorer.oracle.actions.explain.ExplainNode)1 ParserException (net.sourceforge.sqlexplorer.parsers.ParserException)1 QueryParser (net.sourceforge.sqlexplorer.parsers.QueryParser)1 ResultsTab (net.sourceforge.sqlexplorer.sqleditor.results.ResultsTab)1 IStatus (org.eclipse.core.runtime.IStatus)1