use of org.jkiss.dbeaver.model.sql.SQLDataSource in project dbeaver by serge-rider.
the class DatabaseTransferConsumer method generateTargetTableDDL.
public static String generateTargetTableDDL(DBRProgressMonitor monitor, DBPDataSource dataSource, DBSObjectContainer schema, DatabaseMappingContainer containerMapping) throws DBException {
monitor.subTask("Create table " + containerMapping.getTargetName());
StringBuilder sql = new StringBuilder(500);
if (!(dataSource instanceof SQLDataSource)) {
throw new DBException("Data source doesn't support SQL");
}
SQLDataSource targetDataSource = (SQLDataSource) dataSource;
String tableName = DBObjectNameCaseTransformer.transformName(targetDataSource, containerMapping.getTargetName());
containerMapping.setTargetName(tableName);
sql.append("CREATE TABLE ");
if (schema instanceof DBSSchema || schema instanceof DBSCatalog) {
sql.append(DBUtils.getQuotedIdentifier(schema));
sql.append(targetDataSource.getSQLDialect().getCatalogSeparator());
}
sql.append(DBUtils.getQuotedIdentifier(targetDataSource, tableName)).append("(\n");
Map<DBSAttributeBase, DatabaseMappingAttribute> mappedAttrs = new HashMap<>();
for (DatabaseMappingAttribute attr : containerMapping.getAttributeMappings(monitor)) {
if (attr.getMappingType() != DatabaseMappingType.create) {
continue;
}
if (!mappedAttrs.isEmpty())
sql.append(",\n");
appendAttributeClause(dataSource, sql, attr);
mappedAttrs.put(attr.getSource(), attr);
}
if (containerMapping.getSource() instanceof DBSEntity) {
// Make primary key
Collection<? extends DBSEntityAttribute> identifier = DBUtils.getBestTableIdentifier(monitor, (DBSEntity) containerMapping.getSource());
if (!CommonUtils.isEmpty(identifier)) {
boolean idMapped = true;
for (DBSEntityAttribute idAttr : identifier) {
if (!mappedAttrs.containsKey(idAttr)) {
idMapped = false;
break;
}
}
if (idMapped) {
sql.append(",\nPRIMARY KEY (");
boolean hasAttr = false;
for (DBSEntityAttribute idAttr : identifier) {
DatabaseMappingAttribute mappedAttr = mappedAttrs.get(idAttr);
if (hasAttr)
sql.append(",");
sql.append(mappedAttr.getTargetName());
hasAttr = true;
}
sql.append(")\n");
}
}
}
sql.append(")");
return sql.toString();
}
use of org.jkiss.dbeaver.model.sql.SQLDataSource 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.SQLDataSource in project dbeaver by serge-rider.
the class JDBCCallableStatementImpl method findProcedure.
private static DBSProcedure findProcedure(DBCSession session, String queryString) throws DBException {
DBPDataSource dataSource = session.getDataSource();
if (!CommonUtils.isEmpty(queryString)) {
Matcher matcher = EXEC_PATTERN.matcher(queryString);
if (matcher.find()) {
String procName = matcher.group(1);
char divChar = 0;
if (dataSource instanceof SQLDataSource) {
divChar = ((SQLDataSource) dataSource).getSQLDialect().getStructSeparator();
}
if (procName.indexOf(divChar) != -1) {
return findProcedureByNames(session, procName.split("\\" + divChar));
} else {
return findProcedureByNames(session, procName);
}
}
}
return null;
}
use of org.jkiss.dbeaver.model.sql.SQLDataSource in project dbeaver by serge-rider.
the class DBValueFormatting method formatBinaryString.
public static String formatBinaryString(@NotNull DBPDataSource dataSource, @NotNull byte[] data, @NotNull DBDDisplayFormat format, boolean forceLimit) {
DBDBinaryFormatter formatter;
if (format == DBDDisplayFormat.NATIVE && dataSource instanceof SQLDataSource) {
formatter = ((SQLDataSource) dataSource).getSQLDialect().getNativeBinaryFormatter();
} else {
formatter = getBinaryPresentation(dataSource);
}
// Convert bytes to string
int length = data.length;
if (format == DBDDisplayFormat.UI || forceLimit) {
int maxLength = dataSource.getContainer().getPreferenceStore().getInt(ModelPreferences.RESULT_SET_BINARY_STRING_MAX_LEN);
if (length > maxLength) {
length = maxLength;
}
}
String string = formatter.toString(data, 0, length);
if (format == DBDDisplayFormat.NATIVE || length == data.length) {
// Do not append ... for native formatter - it may contain expressions
return string;
}
return string + "..." + " [" + data.length + "]";
}
use of org.jkiss.dbeaver.model.sql.SQLDataSource 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