Search in sources :

Example 1 with SQLQuery

use of org.jkiss.dbeaver.model.sql.SQLQuery in project dbeaver by serge-rider.

the class SQLQueryTransformerCount method transformQuery.

@Override
public SQLQuery transformQuery(SQLDataSource dataSource, SQLQuery query) throws DBException {
    try {
        Statement statement = CCJSqlParserUtil.parse(query.getQuery());
        if (statement instanceof Select && ((Select) statement).getSelectBody() instanceof PlainSelect) {
            PlainSelect select = (PlainSelect) ((Select) statement).getSelectBody();
            List<SelectItem> selectItems = new ArrayList<>();
            Function countFunc = new Function();
            countFunc.setName("count");
            countFunc.setParameters(new ExpressionList(Collections.<Expression>singletonList(new Column("*"))));
            SelectItem countItem = new SelectExpressionItem(countFunc);
            selectItems.add(countItem);
            select.setSelectItems(selectItems);
            return new SQLQuery(dataSource, select.toString(), query, false);
        } else {
            throw new DBException("Query [" + query.getQuery() + "] can't be modified");
        }
    } catch (JSQLParserException e) {
        throw new DBException("Can't transform query to SELECT count(*)", e);
    }
}
Also used : DBException(org.jkiss.dbeaver.DBException) Statement(net.sf.jsqlparser.statement.Statement) SelectExpressionItem(net.sf.jsqlparser.statement.select.SelectExpressionItem) JSQLParserException(net.sf.jsqlparser.JSQLParserException) PlainSelect(net.sf.jsqlparser.statement.select.PlainSelect) ArrayList(java.util.ArrayList) SQLQuery(org.jkiss.dbeaver.model.sql.SQLQuery) Function(net.sf.jsqlparser.expression.Function) Expression(net.sf.jsqlparser.expression.Expression) Column(net.sf.jsqlparser.schema.Column) SelectItem(net.sf.jsqlparser.statement.select.SelectItem) PlainSelect(net.sf.jsqlparser.statement.select.PlainSelect) Select(net.sf.jsqlparser.statement.select.Select) ExpressionList(net.sf.jsqlparser.expression.operators.relational.ExpressionList)

Example 2 with SQLQuery

use of org.jkiss.dbeaver.model.sql.SQLQuery in project dbeaver by serge-rider.

the class SQLEditor method processQueries.

private void processQueries(@NotNull final List<SQLQuery> queries, final boolean newTab, final boolean export, final boolean checkSession) {
    if (queries.isEmpty()) {
        // Nothing to process
        return;
    }
    final DBPDataSourceContainer container = getDataSourceContainer();
    if (checkSession) {
        try {
            DBRProgressListener connectListener = new DBRProgressListener() {

                @Override
                public void onTaskFinished(IStatus status) {
                    if (!status.isOK() || container == null || !container.isConnected()) {
                        UIUtils.showErrorDialog(getSite().getShell(), CoreMessages.editors_sql_error_cant_obtain_session, null, status);
                        return;
                    }
                    // Make a small pause to let all UI connection listeners to finish
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                    // it's ok
                    }
                    DBeaverUI.syncExec(new Runnable() {

                        @Override
                        public void run() {
                            processQueries(queries, newTab, export, false);
                        }
                    });
                }
            };
            if (!checkSession(connectListener)) {
                return;
            }
        } catch (DBException ex) {
            ResultSetViewer viewer = getActiveResultSetViewer();
            if (viewer != null) {
                viewer.setStatus(ex.getMessage(), DBPMessageType.ERROR);
            }
            UIUtils.showErrorDialog(getSite().getShell(), CoreMessages.editors_sql_error_cant_obtain_session, ex.getMessage());
            return;
        }
    }
    if (sashForm.getMaximizedControl() != null) {
        sashForm.setMaximizedControl(null);
    }
    // Save editor
    if (getActivePreferenceStore().getBoolean(SQLPreferenceConstants.AUTO_SAVE_ON_EXECUTE) && isDirty()) {
        doSave(new NullProgressMonitor());
    }
    final boolean isSingleQuery = (queries.size() == 1);
    if (!newTab || !isSingleQuery) {
        // We don't need new tab or we are executing a script - so close all extra tabs
        closeExtraResultTabs(null);
    }
    if (newTab) {
        // Execute each query in a new tab
        for (int i = 0; i < queries.size(); i++) {
            SQLQuery query = queries.get(i);
            QueryProcessor queryProcessor = (i == 0 && !isSingleQuery ? curQueryProcessor : createQueryProcessor(queries.size() == 1));
            queryProcessor.processQueries(Collections.singletonList(query), true, export);
        }
    } else {
        // Use current tab.
        // If current tab was pinned then use first tab
        final QueryResultsContainer firstResults = curQueryProcessor.getFirstResults();
        if (firstResults.isPinned()) {
            curQueryProcessor = queryProcessors.get(0);
        }
        closeExtraResultTabs(curQueryProcessor);
        if (firstResults.tabItem != null) {
            resultTabs.setSelection(firstResults.tabItem);
        }
        curQueryProcessor.processQueries(queries, false, export);
    }
}
Also used : DBException(org.jkiss.dbeaver.DBException) DBRProgressListener(org.jkiss.dbeaver.model.runtime.DBRProgressListener) SQLQuery(org.jkiss.dbeaver.model.sql.SQLQuery) Point(org.eclipse.swt.graphics.Point) ResultSetViewer(org.jkiss.dbeaver.ui.controls.resultset.ResultSetViewer)

Example 3 with SQLQuery

use of org.jkiss.dbeaver.model.sql.SQLQuery in project dbeaver by serge-rider.

the class SQLEditor method processSQL.

public void processSQL(boolean newTab, boolean script, SQLQueryTransformer transformer) {
    IDocument document = getDocument();
    if (document == null) {
        setStatus(CoreMessages.editors_sql_status_cant_obtain_document, DBPMessageType.ERROR);
        return;
    }
    List<SQLQuery> queries;
    if (script) {
        // Execute all SQL statements consequently
        ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
        if (selection.getLength() > 1) {
            queries = extractScriptQueries(selection.getOffset(), selection.getLength());
        } else {
            queries = extractScriptQueries(0, document.getLength());
        }
    } else {
        // Execute statement under cursor or selected text (if selection present)
        SQLQuery sqlQuery = extractActiveQuery();
        if (sqlQuery == null) {
            setStatus(CoreMessages.editors_sql_status_empty_query_string, DBPMessageType.ERROR);
            return;
        } else {
            queries = Collections.singletonList(sqlQuery);
        }
    }
    try {
        if (transformer != null) {
            DBPDataSource dataSource = getDataSource();
            if (dataSource instanceof SQLDataSource) {
                List<SQLQuery> xQueries = new ArrayList<>(queries.size());
                for (int i = 0; i < queries.size(); i++) {
                    SQLQuery query = transformer.transformQuery((SQLDataSource) dataSource, queries.get(i));
                    if (query != null) {
                        xQueries.add(query);
                    }
                }
                queries = xQueries;
            }
        }
    } catch (DBException e) {
        UIUtils.showErrorDialog(getSite().getShell(), "Bad query", "Can't execute query", e);
        return;
    }
    processQueries(queries, newTab, false, true);
}
Also used : DBException(org.jkiss.dbeaver.DBException) SQLQuery(org.jkiss.dbeaver.model.sql.SQLQuery) SQLDataSource(org.jkiss.dbeaver.model.sql.SQLDataSource) Point(org.eclipse.swt.graphics.Point)

Example 4 with SQLQuery

use of org.jkiss.dbeaver.model.sql.SQLQuery in project dbeaver by serge-rider.

the class NavigateQueryHandler method execute.

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    IEditorPart activeEditor = HandlerUtil.getActiveEditor(event);
    if (!(activeEditor instanceof SQLEditorBase)) {
        return null;
    }
    SQLEditorBase editor = (SQLEditorBase) activeEditor;
    String actionId = event.getCommand().getId();
    SQLQuery nextQuery;
    switch(actionId) {
        case CoreCommands.CMD_SQL_QUERY_NEXT:
            nextQuery = editor.extractNextQuery(true);
            break;
        case CoreCommands.CMD_SQL_QUERY_PREV:
            nextQuery = editor.extractNextQuery(false);
            break;
        default:
            nextQuery = null;
            break;
    }
    if (nextQuery != null) {
        editor.selectAndReveal(nextQuery.getOffset(), nextQuery.getLength());
    }
    return null;
}
Also used : SQLEditorBase(org.jkiss.dbeaver.ui.editors.sql.SQLEditorBase) IEditorPart(org.eclipse.ui.IEditorPart) SQLQuery(org.jkiss.dbeaver.model.sql.SQLQuery)

Example 5 with SQLQuery

use of org.jkiss.dbeaver.model.sql.SQLQuery in project dbeaver by serge-rider.

the class SQLQueryJob method executeSingleQuery.

private boolean executeSingleQuery(@NotNull DBCSession session, @NotNull SQLQuery sqlQuery, final boolean fireEvents) {
    lastError = null;
    final DBCExecutionContext executionContext = getExecutionContext();
    final DBPDataSource dataSource = executionContext.getDataSource();
    final SQLQuery originalQuery = sqlQuery;
    long startTime = System.currentTimeMillis();
    boolean startQueryAlerted = false;
    if (!prepareStatementParameters(sqlQuery)) {
        return false;
    }
    // Modify query (filters + parameters)
    if (dataFilter != null && dataFilter.hasFilters() && dataSource instanceof SQLDataSource) {
        String filteredQueryText = ((SQLDataSource) dataSource).getSQLDialect().addFiltersToQuery(dataSource, originalQuery.getQuery(), dataFilter);
        sqlQuery = new SQLQuery(executionContext.getDataSource(), filteredQueryText, sqlQuery);
    }
    final SQLQueryResult curResult = new SQLQueryResult(sqlQuery);
    if (rsOffset > 0) {
        curResult.setRowOffset(rsOffset);
    }
    try {
        // Prepare statement
        closeStatement();
        // Check and invalidate connection
        if (!connectionInvalidated && dataSource.getContainer().getPreferenceStore().getBoolean(DBeaverPreferences.STATEMENT_INVALIDATE_BEFORE_EXECUTE)) {
            executionContext.invalidateContext(session.getProgressMonitor());
            connectionInvalidated = true;
        }
        statistics.setQueryText(originalQuery.getQuery());
        // Notify query start
        if (fireEvents && listener != null) {
            // Notify query start
            try {
                listener.onStartQuery(session, sqlQuery);
            } catch (Exception e) {
                log.error(e);
            }
            startQueryAlerted = true;
        }
        startTime = System.currentTimeMillis();
        DBCExecutionSource source = new AbstractExecutionSource(dataContainer, executionContext, partSite.getPart(), sqlQuery);
        final DBCStatement dbcStatement = DBUtils.makeStatement(source, session, DBCStatementType.SCRIPT, sqlQuery, rsOffset, rsMaxRows);
        curStatement = dbcStatement;
        int statementTimeout = getDataSourceContainer().getPreferenceStore().getInt(DBeaverPreferences.STATEMENT_TIMEOUT);
        if (statementTimeout > 0) {
            try {
                dbcStatement.setStatementTimeout(statementTimeout);
            } catch (Throwable e) {
                log.debug("Can't set statement timeout:" + e.getMessage());
            }
        }
        // Execute statement
        try {
            boolean hasResultSet = dbcStatement.executeStatement();
            curResult.setHasResultSet(hasResultSet);
            statistics.addExecuteTime(System.currentTimeMillis() - startTime);
            statistics.addStatementsCount();
            long updateCount = -1;
            while (hasResultSet || resultSetNumber == 0 || updateCount >= 0) {
                // Fetch data only if we have to fetch all results or if it is rs requested
                if (fetchResultSetNumber < 0 || fetchResultSetNumber == resultSetNumber) {
                    if (hasResultSet && fetchResultSets) {
                        DBDDataReceiver dataReceiver = resultsConsumer.getDataReceiver(sqlQuery, resultSetNumber);
                        if (dataReceiver != null) {
                            hasResultSet = fetchQueryData(session, dbcStatement.openResultSet(), curResult, dataReceiver, true);
                        }
                    }
                }
                if (!hasResultSet) {
                    try {
                        updateCount = dbcStatement.getUpdateRowCount();
                        if (updateCount >= 0) {
                            curResult.setUpdateCount(updateCount);
                            statistics.addRowsUpdated(updateCount);
                        }
                    } catch (DBCException e) {
                        // In some cases we can't read update count
                        // This is bad but we can live with it
                        // Just print a warning
                        log.warn("Can't obtain update count", e);
                    }
                }
                if (hasResultSet && fetchResultSets) {
                    resultSetNumber++;
                    fetchResultSetNumber = resultSetNumber;
                }
                if (!hasResultSet && updateCount < 0) {
                    // Nothing else to fetch
                    break;
                }
                if (dataSource.getInfo().supportsMultipleResults()) {
                    hasResultSet = dbcStatement.nextResults();
                    updateCount = hasResultSet ? -1 : 0;
                } else {
                    break;
                }
            }
            try {
                curResult.setWarnings(dbcStatement.getStatementWarnings());
            } catch (Throwable e) {
                log.warn("Can't read execution warnings", e);
            }
        } finally {
            //monitor.subTask("Close query");
            if (!keepStatementOpen()) {
                closeStatement();
            }
        }
    } catch (Throwable ex) {
        if (!(ex instanceof DBException)) {
            log.error("Unexpected error while processing SQL", ex);
        }
        curResult.setError(ex);
        lastError = ex;
    } finally {
        curResult.setQueryTime(System.currentTimeMillis() - startTime);
        if (fireEvents && listener != null && startQueryAlerted) {
            // Notify query end
            try {
                listener.onEndQuery(session, curResult);
            } catch (Exception e) {
                log.error(e);
            }
        }
    }
    if (curResult.getError() != null && errorHandling != SQLScriptErrorHandling.IGNORE) {
        return false;
    }
    // Success
    lastGoodQuery = originalQuery;
    return true;
}
Also used : DBException(org.jkiss.dbeaver.DBException) SQLQueryResult(org.jkiss.dbeaver.model.sql.SQLQueryResult) DBDDataReceiver(org.jkiss.dbeaver.model.data.DBDDataReceiver) DBPDataSource(org.jkiss.dbeaver.model.DBPDataSource) SQLQuery(org.jkiss.dbeaver.model.sql.SQLQuery) SQLDataSource(org.jkiss.dbeaver.model.sql.SQLDataSource) DBException(org.jkiss.dbeaver.DBException) AbstractExecutionSource(org.jkiss.dbeaver.model.impl.AbstractExecutionSource)

Aggregations

SQLQuery (org.jkiss.dbeaver.model.sql.SQLQuery)17 DBException (org.jkiss.dbeaver.DBException)5 DBPDataSource (org.jkiss.dbeaver.model.DBPDataSource)4 Point (org.eclipse.swt.graphics.Point)3 DBRProgressMonitor (org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)3 DBSTable (org.jkiss.dbeaver.model.struct.rdb.DBSTable)3 DBDDataReceiver (org.jkiss.dbeaver.model.data.DBDDataReceiver)2 SQLDataSource (org.jkiss.dbeaver.model.sql.SQLDataSource)2 DBVEntityConstraint (org.jkiss.dbeaver.model.virtual.DBVEntityConstraint)2 FileReader (java.io.FileReader)1 IOException (java.io.IOException)1 Reader (java.io.Reader)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 ArrayList (java.util.ArrayList)1 JSQLParserException (net.sf.jsqlparser.JSQLParserException)1 Expression (net.sf.jsqlparser.expression.Expression)1 Function (net.sf.jsqlparser.expression.Function)1 ExpressionList (net.sf.jsqlparser.expression.operators.relational.ExpressionList)1 Column (net.sf.jsqlparser.schema.Column)1 Statement (net.sf.jsqlparser.statement.Statement)1