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);
}
}
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);
}
}
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);
}
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;
}
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;
}
Aggregations